简体   繁体   English

Selenium 在无头模式下无法正常工作

[英]Selenium not working properly with headless mode

I am trying to extract the text of the first listing from the url using Selenium and headless browser.我正在尝试使用 Selenium 和无头浏览器从 url 中提取第一个列表的文本。 The code works fine if it's not in headless mode, but not returning anything and not working fine in headless mode.如果代码不在无头模式下,则代码可以正常工作,但不返回任何内容并且在无头模式下无法正常工作。 Here's the code.这是代码。

import requests  
import time
from selenium import webdriver  
from selenium.webdriver.firefox.options import Options as FirefoxOptions 
user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'  

options = FirefoxOptions()  
options.add_argument(f'user-agent={user_agent}')  
options.add_argument("--headless")  
options.add_argument('window-size=1920x1080')  
driver = webdriver.Firefox(options=options)  
start_url = "https://ammoseek.com/ammo/300aac-blackout?pl=no&co=new&ca=brass" #works with US IP
driver.get(start_url)  
time.sleep(5)  
text = driver.find_element_by_class_name('results-card').text  
print (text)

Try to run your code without specifying user-agent .尝试在不指定user-agent的情况下运行您的代码。

You may also try to use Google Chrome webdriver instead.您也可以尝试改用 Google Chrome 网络驱动程序。

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

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