使用Selenium Python开发购物机器人自动登录失败问题求助
导致该问题的核心原因是目标网站的反爬机制识别到了Selenium的自动化浏览器特征,拦截了登录请求,手动操作时不存在这些特征,所以可以正常登录。可按以下方案调整代码:
- 隐藏浏览器自动化标识
Selenium默认启动的Chrome会暴露enable-automation、navigator.webdriver=true等特征,极易被反爬系统识别,需要通过启动参数和CDP指令关闭这些特征。 - 模拟真人操作节奏
避免页面加载后立刻执行输入、点击操作,输入账号密码时增加随机间隔,模拟真人输入速度,降低机器操作特征。 - 修正无效配置
implicitly_wait为全局隐式等待配置,仅需在driver初始化后设置一次即可,重复设置不会生效。
修改后的参考代码:
import time import random from selenium import webdriver from selenium.webdriver.common.keys import Keys # 配置Chrome启动参数,隐藏自动化特征 options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) options.add_argument("--disable-blink-features=AutomationControlled") # 初始化driver,注意路径前加r避免转义字符问题 driver = webdriver.Chrome( executable_path=r"D:\Fiverr\Practice\chromedriver_win32\chromedriver.exe", options=options ) # 全局隐式等待仅需设置一次 driver.implicitly_wait(15) # 注入JS修改webdriver属性 driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) driver.get("https://www.finewineandgoodspirits.com") time.sleep(random.uniform(1,2)) driver.find_element_by_xpath("//*[@id='ageVerify']/div[3]/div[1]").click() time.sleep(random.uniform(0.5,1.5)) driver.find_element_by_class_name("ltkpopup-close").click() time.sleep(random.uniform(1,2)) driver.get("https://www.finewineandgoodspirits.com/webapp/wcs/stores/servlet/LogonForm?langId=-1&storeId=10051&catalogId=10051") time.sleep(random.uniform(1,2)) # 模拟真人分段输入邮箱 email = driver.find_element_by_name("logonId") email_content = "mccallister81@gmail.com" for c in email_content: email.send_keys(c) time.sleep(random.uniform(0.05, 0.2)) time.sleep(random.uniform(0.5,1)) # 模拟真人分段输入密码 password = driver.find_element_by_name("logonPassword") password_content = "Envision1" for c in password_content: password.send_keys(c) time.sleep(random.uniform(0.05, 0.2)) time.sleep(random.uniform(0.5,1)) driver.find_element_by_id("loginButton").click()
如果调整后仍登录失败,可尝试更换浏览器UA、添加代理IP,进一步降低特征重合度。
内容的提问来源于stack exchange,提问作者Moazam Shahid
相关产品推荐
相关产品推荐

