7d5339acad
Reemplaza todos los time.Sleep arbitrarios por esperas basadas en eventos CDP. Cambios: - examples/basic.go: usa WaitUntil en Navigate - cmd/navegar.go: elimina sleeps después de acciones - cmd/buscar.go y buscar_v2.go: usa networkidle - cmd/list_blog.go: elimina sleep innecesario - main.go: usa WaitUntil load Mejora performance y robustez al no esperar más de lo necesario. Archivos: examples/basic.go, cmd/*.go, main.go
119 lines
3.5 KiB
Go
119 lines
3.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"navegator/pkg/browser"
|
|
)
|
|
|
|
func main() {
|
|
// Parámetros
|
|
url := flag.String("url", "", "URL a visitar (requerido)")
|
|
profile := flag.String("profile", "user-default", "Perfil de navegador a usar")
|
|
headless := flag.Bool("headless", false, "Modo headless (default: false para ver la navegación)")
|
|
duration := flag.Int("duration", 10, "Segundos que mantener abierto el navegador")
|
|
click := flag.String("click", "", "Selector CSS para hacer click (opcional)")
|
|
type_ := flag.String("type", "", "Selector CSS donde escribir (opcional)")
|
|
text := flag.String("text", "", "Texto a escribir (requiere -type)")
|
|
|
|
flag.Parse()
|
|
|
|
if *url == "" {
|
|
fmt.Println("Error: debes proporcionar una URL con -url")
|
|
fmt.Println("\nEjemplo básico:")
|
|
fmt.Println(" ./navegar -url https://example.com -profile usuario1")
|
|
fmt.Println("\nEjemplo con interacción:")
|
|
fmt.Println(" ./navegar -url https://example.com -click 'a[href]' -duration 30")
|
|
fmt.Println("\nEjemplo con formulario:")
|
|
fmt.Println(" ./navegar -url https://httpbin.org/forms/post -type 'input[name=\"custname\"]' -text 'Juan Pérez'")
|
|
fmt.Println("\nOpciones:")
|
|
flag.PrintDefaults()
|
|
os.Exit(1)
|
|
}
|
|
|
|
ctx := context.Background()
|
|
|
|
// Configurar navegador
|
|
currentDir, _ := os.Getwd()
|
|
profilesDir := filepath.Join(currentDir, "perfiles")
|
|
|
|
config := browser.DefaultConfig()
|
|
config.ProfilesBaseDir = profilesDir
|
|
config.ProfileName = *profile
|
|
config.StealthFlags.Headless = *headless
|
|
config.StealthFlags.WindowSize = [2]int{1280, 720}
|
|
|
|
log.Printf("🌐 Navegando: %s", *url)
|
|
log.Printf("👤 Perfil: %s", *profile)
|
|
log.Printf("⏱️ Duración: %d segundos", *duration)
|
|
|
|
// Lanzar navegador
|
|
b, err := browser.Launch(ctx, config)
|
|
if err != nil {
|
|
log.Fatalf("❌ Error: %v", err)
|
|
}
|
|
defer b.Close()
|
|
|
|
// Iniciar recording
|
|
recordingFile := filepath.Join(currentDir, fmt.Sprintf("recording_%s.log", *profile))
|
|
if err := b.StartRecording(recordingFile); err != nil {
|
|
log.Printf("⚠️ Recording desactivado: %v", err)
|
|
} else {
|
|
log.Printf("📝 Recording: %s", recordingFile)
|
|
}
|
|
|
|
b.AddComment(fmt.Sprintf("=== Sesión de %s ===", *profile))
|
|
|
|
// Navegar
|
|
opts := browser.DefaultNavigateOptions()
|
|
opts.Timeout = 30 * time.Second
|
|
|
|
if err := b.Navigate(ctx, *url, opts); err != nil {
|
|
log.Printf("⚠️ Advertencia: %v", err)
|
|
} else {
|
|
log.Println("✅ Página cargada")
|
|
}
|
|
|
|
// Click si se especificó
|
|
if *click != "" {
|
|
b.AddComment(fmt.Sprintf("Click en: %s", *click))
|
|
log.Printf("🖱️ Haciendo click en: %s", *click)
|
|
if err := b.Click(ctx, *click); err != nil {
|
|
log.Printf("⚠️ Error al hacer click: %v", err)
|
|
} else {
|
|
log.Println("✅ Click realizado")
|
|
}
|
|
}
|
|
|
|
// Type si se especificó
|
|
if *type_ != "" && *text != "" {
|
|
b.AddComment(fmt.Sprintf("Escribiendo en: %s", *type_))
|
|
log.Printf("⌨️ Escribiendo '%s' en: %s", *text, *type_)
|
|
if err := b.Type(ctx, *type_, *text, nil); err != nil {
|
|
log.Printf("⚠️ Error al escribir: %v", err)
|
|
} else {
|
|
log.Println("✅ Texto escrito")
|
|
}
|
|
}
|
|
|
|
// Obtener información de la página
|
|
title, _ := b.Evaluate(ctx, "document.title")
|
|
log.Printf("📄 Título: %v", title.Value)
|
|
|
|
currentURL, _ := b.Evaluate(ctx, "window.location.href")
|
|
log.Printf("🔗 URL actual: %v", currentURL.Value)
|
|
|
|
// Mantener navegador abierto
|
|
log.Printf("\n⏳ Manteniendo navegador abierto por %d segundos...", *duration)
|
|
time.Sleep(time.Duration(*duration) * time.Second)
|
|
|
|
b.AddComment("Sesión finalizada")
|
|
log.Println("✨ Completado!")
|
|
}
|