繁体   English   中英

使用带有 python selenium 的无头 chrome 时出现“403 Forbidden”错误

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

使用常规 chromedriver 时,我的测试运行没有任何问题,并且我得到了测试结果。 When I am trying to launch headless chrome with python and selenium, I get a '403 Forbidden' error on the screenshot and selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: on the console. 我通过了所有这些 arguments 仍然得到相同的结果:

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)

我找到了另一个类似于第一个答案的解决方案。可以在此处找到该问题的解释。 这为我解决了这个问题。

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM