使用 headless chrome 和 python selenium 时出现“403 Forbidden”错误

Getting '403 Forbidden' error when using headless chrome with python selenium

使用常规 chrome 驱动程序时,我的测试 运行 没有任何问题,我得到了测试结果。当我尝试使用 python 和 selenium 启动无头 chrome 时,我在屏幕截图上收到“403 Forbidden”错误,在控制台上收到 selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:。我传递了所有这些参数,但仍然得到相同的结果:

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)

我也尝试了 from fake_headers import Headers 但问题仍然存在

#!/usr/bin/python3
#try this 
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time,os
from bs4 import BeautifulSoup
from pyvirtualdisplay import Display
from fake_useragent import UserAgent
def web(url):
    display = Display(visible=0, size=(1920, 1080)) 
    display.start()
    ua = UserAgent()
    userAgent = ua.chrome
    chrome_options = Options()
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    chrome_options.add_argument(f'user-agent={userAgent}')
    driver = webdriver.Chrome (options = chrome_options)
    driver.get(url)

我找到了另一个类似于第一个答案的解决方案。 The explanation for the issue can be found here. 这为我解决了这个问题。

chrome_options = Options()
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
chrome_options.add_argument(f'user-agent={user_agent}')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)

是的,您遇到了“用户代理”问题,但建议对具有反机器人保护的网页使用 display(),尽管此解决方案是临时的。 我的主要语言是西班牙语