Python 仅在 ChromeDriver 无头模式下请求 Selenium 问题

问题描述 投票:0回答:1

我想使用请求库和 Selenium 与 ChromeDriver 来抓取 Facebook 广告网站(因为我需要在具有 chromedriver 的 pythonanywhere 上运行它)。

所以我这样做:


chrome_options = ChromeOptions()

arguments = [
    "--disable-notifications",
    "--start-maximized",
    "disable-infobars",
    "--disable-gpu",
    "--headless",
    "window-size=1980,1080",
    "--allow-running-insecure-content",
    "--disable-extensions",
    "--no-sandbox",
    "--ignore-certificate-errors",
    "--test-type",
    "--disable-web-security",
    "--safebrowsing-disable-download-protection"
]

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")

# Path to your ChromeDriver
chrome_driver_path = "/usr/local/bin/chromedriver"  # This is typically the path on PythonAnywhere

# Set up the WebDriver
service = ChromeService(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)

安装驱动程序,然后抓取页面:

def scrape_page(companyId, companyName):
    # Navigate to the Facebook Ads Library page
    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(5) 
print(driver.page_source)

当然,睡眠不利于长期使用。我应该使用 WebDriverWait。但现在我想让它发挥作用。

但是它打印的是带有脚本标签的 HTML。看起来页面未正确加载。当我删除无头时,我看到浏览器正在正确运行并加载页面,并且脚本会打印加载的所有内容。

有什么想法如何做到这一点吗?

python selenium-webdriver selenium-chromedriver
1个回答
0
投票

您应该使用 WebDriverWait 直到出现一个元素。 (文档

您无法确定驱动程序在无头模式下会做什么,因此您需要确保使用 waitUntil 而不是简单的睡眠。

WebDriverWait(driver, 20).until(
        EC.presence_of_element_located(
            (By.CSS_SELECTOR, "element"))
    )
© www.soinside.com 2019 - 2024. All rights reserved.