ChromeDriver无头模式下Selenium爬取Facebook广告库加载异常问题
解决PythonAnywhere无头Chrome爬取Facebook广告库页面加载不全问题
在PythonAnywhere环境中使用Selenium+ChromeDriver爬取Facebook广告库时,开启无头模式后页面仅返回包含script标签的空HTML,关闭无头模式则能正常加载完整内容,这是因为旧版无头Chrome的环境特征与正常浏览器差异明显,容易被反爬机制识别拦截,同时配置参数存在小错误。可以通过以下调整解决:
关键调整点
- 修正参数前缀:原配置中
disable-infobars和window-size=1980,1080缺少--前缀,属于无效参数,需补全。 - 切换新版无头模式:将
--headless替换为--headless=new,新版无头模式的运行环境更接近正常Chrome浏览器,大幅降低被反爬检测的概率。 - 添加防自动化检测参数:加入
--disable-blink-features=AutomationControlled,避免Chrome暴露自动化工具的特征。
修改后的完整配置代码
from selenium.webdriver.chrome.options import ChromeOptions from selenium.webdriver.chrome.service import ChromeService from selenium import webdriver chrome_options = ChromeOptions() arguments = [ "--disable-notifications", "--start-maximized", "--disable-infobars", # 补全--前缀 "--disable-gpu", "--headless=new", # 替换为新版无头模式 "--window-size=1980,1080", # 补全--前缀 "--allow-running-insecure-content", "--disable-extensions", "--no-sandbox", "--ignore-certificate-errors", "--test-type", "--disable-web-security", "--safebrowsing-disable-download-protection", "--disable-blink-features=AutomationControlled" # 添加防检测参数 ] for argument in arguments: chrome_options.add_argument(argument) prefs = { "intl.accept_languages": "en-US" } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") # PythonAnywhere上的ChromeDriver路径 chrome_driver_path = "/usr/local/bin/chromedriver" service = ChromeService(executable_path=chrome_driver_path) driver = webdriver.Chrome(service=service, options=chrome_options)
爬取代码调整(可选优化)
虽然你暂时使用time.sleep,可以适当延长等待时间确保页面加载完成,后续建议替换为WebDriverWait等待目标元素出现:
import time def scrape_page(companyId, companyName): url = f'https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=NL&view_all_page_id={companyId}&search_type=page&media_type=all' driver.get(url) time.sleep(8) # 适当延长等待时间,确保JS渲染完成 print(driver.page_source)
内容的提问来源于stack exchange,提问作者FrancMo
相关产品推荐
相关产品推荐

