使用Selenium爬取图片遇安全校验页面无法访问求助
解决Selenium访问网站时的安全检查跳转问题
你遇到的是网站的反爬机制(比如Cloudflare类安全验证),它检测到你使用的是自动化工具,所以跳转到了安全检查页面。试试下面这些解决方案:
一、配置Firefox Profile,隐藏自动化特征
Firefox Profile能帮你模拟真实用户的浏览器配置,避免被识别为机器人。修改代码如下:
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service # 创建Firefox配置对象 profile = webdriver.FirefoxProfile() # 禁用WebDriver标识,防止网站检测 profile.set_preference("dom.webdriver.enabled", False) profile.set_preference("useAutomationExtension", False) # 设置真实浏览器的User-Agent profile.set_preference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0") options = Options() options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe" options.headless = True # 将配置绑定到options options.profile = profile driver = webdriver.Firefox(service=Service(r"D:\Program\geckodriver\geckodriver.exe"), options=options) driver.implicitly_wait(10) driver.get(url)
二、关闭无头模式临时排查
无头模式更容易被网站识别,你可以先关闭它,让浏览器窗口显示出来,观察是否需要手动完成验证,或是页面有其他提示:
options.headless = False # 改为False,显示浏览器窗口
三、添加显式等待,适配验证加载时间
部分安全验证需要一定加载时间,你可以添加显式等待,等待页面核心元素出现后再继续操作:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 访问页面后,等待目标网站的标志性元素(比如页面图片)出现 WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.TAG_NAME, "img")) )
如果以上方法仍无效,可能是网站用了更严格的反爬机制,你可以尝试undetected-chromedriver这类专门绕过反爬的工具,不过优先把上面的基础配置调整到位。
内容的提问来源于stack exchange,提问作者Hoàng Anh Nguyễn
相关产品推荐
相关产品推荐

