我目前正在使用 Python 和 Selenium 自动化我的 Twitter 帐户的登录过程。
但是,我面临一个问题,Twitter 的反机器人措施似乎检测到自动化,并在单击 下一步按钮时立即将我重定向到主页。
我尝试使用send_keys
和 ActionChains 来创建更多类似人类的交互,但问题仍然存在。这是一个简化的代码片段,说明了我当前的方法:
# imports...
driver.get(URLS.login)
username_input = driver.find_element(By.NAME, 'text')
username_input.send_keys(username)
next_button = driver.find_element(By.XPATH, '//div[@role="button"]')
# These attempts all failed and return to the homepage
next_button.click()
next_button.send_keys(Keys.ENTER)
ActionChains(driver).move_to_element(next_button).click().perform()
奇怪的是,除了手动点击下一步按钮外,在控制台中执行click
import time
from selenium import webdriver
from selenium.webdriver import ChromeOptions, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
options = ChromeOptions()
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
driver = webdriver.Chrome(options=options)
url = "https://twitter.com/i/flow/login"
driver.get(url)
username = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[autocomplete="username"]')))
username.send_keys("your_username")
username.send_keys(Keys.ENTER)
password = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[name="password"]')))
password.send_keys("your_password")
password.send_keys(Keys.ENTER)
time.sleep(10)