python - 通过 Selenium Python 在正常/ headless 模式下使用 ChromeDriver/Chrome 访问 Cloudflare 网站有什么区别

标签 python selenium selenium-chromedriver cloudflare google-chrome-headless

我有一个关于 --headless 的问题用于 Chrome 的 Python Selenium 中的模式。

代码

 from selenium import webdriver
 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

 CHROME_DRIVER_DIR = "selenium/chromedriver"

 chrome_options = webdriver.ChromeOptions()
 caps = DesiredCapabilities().CHROME
 chrome_options.add_argument("--disable-dev-shm-usage")
 chrome_options.add_argument("--remote-debugging-port=9222")
 chrome_options.add_argument("--headless")  # Runs Chrome in headless mode.
 chrome_options.add_argument('--no-sandbox')  # # Bypass OS security model
 chrome_options.add_argument("--disable-extensions")
 chrome_options.add_argument("--disable-gpu")

 browser = webdriver.Chrome(desired_capabilities=caps, executable_path=CHROME_DRIVER_DIR, options=chrome_options)

 browser.get("https://www.manta.com/c/mm2956g/mashuda-contractors")
 print(browser.page_source)
 browser.quit()

当我删除 chrome_options.add_argument("--headless")一切正常,但有了这个--headless*下一个问题
Please enable cookies.

Error 1020 Ray ID: 53fd62b4087d8116 • 2019-12-04 11:19:28 UTC

Access denied

What happened?
This website is using a security service to protect itself from online attacks.

Cloudflare Ray ID: 53fd62b4087d8116 • Your IP: 168.81.117.111 • Performance & security by Cloudflare

普通模式和 --headless 有什么区别? ?

最佳答案

这是 HTTP User-Agent Cloudflare 不喜欢的 header 。
要解决此问题,只需更改您的 user-agent chrome 选项(以下代码适用于 Python 中的 Selenium):

option.add_argument('--headless')
option.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36")

关于python - 通过 Selenium Python 在正常/ headless 模式下使用 ChromeDriver/Chrome 访问 Cloudflare 网站有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59174899/

相关文章:

python - 如何通过 Pandas 中特定列的计算添加行

python - 从具有 'different date format"的数据框中的日期列中提取年份 - python

python - 如何根据其他列中的多个条件更新列数据?

javascript - 识别 Protractor 测试失败的断言

java - 警报 - Selenium

glibc - 在 CentOS6 中运行 chromedriver : "/lib64/libc.so.6: version ` GLIBC_2. 1 4' not found"时出错

java - Selenium 错误: "org.openqa.selenium.SessionNotCreatedException: session not created from tab crashed" after update electron engine to 9. 0.3

Python-Matplotlib 箱线图。如何显示百分位数 0、10、25、50、75、90 和 100?

python - Selenium:启动 Chromedriver 时隐藏命令提示符窗口?

java - 如何使用selenium获取标题标签内的 anchor 标签值和href值