Crear cuentas de Gmail manualmente puede resultar tedioso, especialmente si necesita varias cuentas para realizar pruebas u otros fines. En este tutorial, aprenderá cómo automatizar el proceso de registro de la cuenta de Gmail usando Python y Selenium. Además, usaremos el faker
biblioteca para generar datos de usuario aleatorios, random
para la generación de contraseñas, y webdriver-manager
y PySocks
para manejar apoderados.
Requisitos previos
Antes de comenzar, asegúrese de tener instalado lo siguiente:
- Pitón 3.x
- Selenio
- Controlador web de Chrome
- farsante
- calcetines
- Administrador de WebDriver para Selenium
Puede instalar Selenium, Faker, PySocks y WebDriver Manager usando pip:
pip install selenium faker pysocks webdriver-manager
Descargue Chrome WebDriver desde aquí y asegúrese de que esté en su RUTA.
Descripción general del guión
El guión:
- Genere nombre, apellido, nombre de usuario y contraseña aleatorios.
- Abra la página de registro de Gmail usando Selenium.
- Rellena el formulario de registro con los datos generados.
- Envíe el formulario.
- Utilice un proxy SOCKS5 para el proceso de registro.
Paso 1: importar bibliotecas e inicializar Faker
Primero, importaremos las bibliotecas necesarias e inicializaremos Faker
:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from faker import Faker
import random
import string
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Initialize Faker
fake = Faker()
Paso 2: generar datos aleatorios
A continuación, crearemos una función para generar una contraseña aleatoria y generar los datos de usuario aleatorios:
# Function to generate a random password
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
# Generate random user data
first_name = fake.first_name()
last_name = fake.last_name()
username = first_name.lower() + last_name.lower() + str(random.randint(1000, 9999))
password = generate_password()
Paso 3: Inicialice Selenium WebDriver con Proxy
Inicialice Chrome WebDriver y navegue hasta la página de registro de Gmail, utilizando un proxy SOCKS5:
# Proxy settings (replace with your proxy details)
proxy = "your_proxy_address:your_proxy_port"
# Initialize Chrome WebDriver with proxy settings
chrome_options = Options()
chrome_options.add_argument("--proxy-server=socks5://" + proxy)
# Initialize the WebDriver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
# Open Gmail signup page
driver.get("https://accounts.google.com/signup")
Paso 4: complete el formulario de registro
Espere a que se cargue la página, ubique los campos del formulario y rellénelos con los datos generados:
# Wait for the page to load and locate the form fields
wait = WebDriverWait(driver, 10)
first_name_field = wait.until(EC.presence_of_element_located((By.ID, "firstName")))
last_name_field = driver.find_element(By.ID, "lastName")
username_field = driver.find_element(By.ID, "username")
password_field = driver.find_element(By.NAME, "Passwd")
confirm_password_field = driver.find_element(By.NAME, "ConfirmPasswd")
# Fill out the form fields
first_name_field.send_keys(first_name)
last_name_field.send_keys(last_name)
username_field.send_keys(username)
password_field.send_keys(password)
confirm_password_field.send_keys(password)
Paso 5: envíe el formulario
Envíe el formulario y agregue un retraso para permitir que se cargue la siguiente página:
# Submit the form
next_button = driver.find_element(By.XPATH, '//*[@id="accountDetailsNext"]/div/button')
next_button.click()
# Add a delay to allow the next page to load (you may need to adjust the sleep time)
time.sleep(5)
Paso 6: realice pasos adicionales
Dependiendo del proceso de registro de Google, es posible que deba realizar pasos adicionales como verificación telefónica, correo electrónico de recuperación o CAPTCHA. Esta parte variará y puede requerir un manejo más avanzado.
Paso 7: cierra el navegador
Cierra el navegador una vez que se complete el proceso:
# Close the browser after the process is complete
driver.quit()
# Output the generated data
print(f"First Name: {first_name}")
print(f"Last Name: {last_name}")
print(f"Username: {username}")
print(f"Password: {password}")
Guión completo
Aquí está el script completo que combina todos los pasos:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from faker import Faker
import random
import string
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Initialize Faker
fake = Faker()
# Function to generate a random password
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
# Generate random user data
first_name = fake.first_name()
last_name = fake.last_name()
username = first_name.lower() + last_name.lower() + str(random.randint(1000, 9999))
password = generate_password()
# Proxy settings (replace with your proxy details)
proxy = "your_proxy_address:your_proxy_port"
# Initialize Chrome WebDriver with proxy settings
chrome_options = Options()
chrome_options.add_argument("--proxy-server=socks5://" + proxy)
# Initialize the WebDriver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
# Open Gmail signup page
driver.get("https://accounts.google.com/signup")
# Wait for the page to load and locate the form fields
wait = WebDriverWait(driver, 10)
first_name_field = wait.until(EC.presence_of_element_located((By.ID, "firstName")))
last_name_field = driver.find_element(By.ID, "lastName")
username_field = driver.find_element(By.ID, "username")
password_field = driver.find_element(By.NAME, "Passwd")
confirm_password_field = driver.find_element(By.NAME, "ConfirmPasswd")
# Fill out the form fields
first_name_field.send_keys(first_name)
last_name_field.send_keys(last_name)
username_field.send_keys(username)
password_field.send_keys(password)
confirm_password_field.send_keys(password)
# Submit the form
next_button = driver.find_element(By.XPATH, '//*[@id="accountDetailsNext"]/div/button')
next_button.click()
# Add a delay to allow the next page to load (you may need to adjust the sleep time)
time.sleep(5)
# Close the browser after the process is complete
driver.quit()
# Output the generated data
print(f"First Name: {first_name}")
print(f"Last Name: {last_name}")
print(f"Username: {username}")
print(f"Password: {password}")
Conclusión
Ha automatizado con éxito el proceso de registro de la cuenta de Gmail utilizando Python y Selenium, con la adición de compatibilidad con proxy SOCKS5. Este script genera datos de usuario aleatorios, completa el formulario de registro y dirige el tráfico a través de un proxy específico.
Recuerde reemplazar your_proxy_address:your_proxy_port
con sus detalles reales de proxy y utilice este script de manera responsable, teniendo en cuenta las implicaciones legales y éticas de automatizar la creación de cuentas.