【问题标题】:Python Selenium Chromedriver not working with --headless optionPython Selenium Chromedriver 不适用于 --headless 选项
【发布时间】:2019-06-04 01:02:46
【问题描述】:

我正在运行 chromedriver 来尝试从网站上抓取一些数据。没有无头选项,一切正常。但是,当我添加选项时,webdriver 需要很长时间才能加载 url,并且当我尝试查找一个元素(在没有 --headless 的情况下运行时找到)时,我收到一个错误。

使用打印语句并在url“加载”后获取html,我发现没有html,它是空的(见下面的输出)。

class Fidelity:
    def __init__(self):
        self.url = 'https://eresearch.fidelity.com/eresearch/gotoBL/fidelityTopOrders.jhtml'
        self.options = Options()
        self.options.add_argument("--headless")
        self.options.add_argument("--window-size=1500,1000")
        self.driver = webdriver.Chrome(executable_path='.\\dependencies\\chromedriver.exe', options = self.options)
        print("init")

    def initiate_browser(self):
        self.driver.get(self.url)
        time.sleep(5)
        script = self.driver.execute_script("return document.documentElement.outerHTML")
        print(script)
        print("got url")

    def find_orders(self):
        wait = WebDriverWait(self.driver, 15)
        data= wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]'))) #ERROR ON THIS LINE

这是整个输出:

init
<html><head></head><body></body></html>
url
Traceback (most recent call last):
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 102, in <module>
    orders = scrape.find_tesla_orders()
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 75, in find_tesla_orders
    tesla = self.driver.find_element_by_xpath("//a[@href='https://qr.fidelity.com/embeddedquotes/redirect/research?symbol=TSLA']")
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='https://qr.fidelity.com/embeddedquotes/redirect/research?symbol=TSLA']"}
  (Session info: headless chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

更新代码的新错误:

init
<html><head></head><body></body></html>
url
Traceback (most recent call last):
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 104, in <module>
    orders = scrape.find_tesla_orders()
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 76, in find_tesla_orders
    tesla = wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]')))
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

我尝试通过谷歌找到答案,但没有任何建议有效。其他人对某些网站有这个问题吗?任何帮助表示赞赏。

更新

不幸的是,这个脚本仍然无法运行,webdriver 在无头时由于某种原因无法正确加载页面,即使在没有使用无头选项运行此脚本的情况下一切正常。

【问题讨论】:

  • 试试firefox,我也从start bage开始得到chrome-vebdriver,忽略url和--headless
  • 非常感谢。我不知道为什么我没有考虑尝试不同的浏览器。我一直用铬。不知道为什么有些网站不能使用 chrome headless。无论如何,谢谢。

标签: python selenium-webdriver selenium-chromedriver


【解决方案1】:

对于将来想解决此问题的任何人,某些网站无法使用 chrome 的无头选项正确加载。我不认为有办法解决这个问题。只需使用不同的浏览器(如 Firefox)。感谢 user8426627。

【讨论】:

  • 为我工作。一旦我从 Chrome 驱动程序切换到 Firefox 驱动程序,我的脚本就会在无头模式下工作。谢谢!
  • 这对我有用!!!尝试从 Chrome 切换到 Firefox 并使用带有 --headless 标志的 geckodriver,它应该可以工作。不确定是什么差异导致了问题。
【解决方案2】:

您是否尝试过使用用户代理?

我遇到了同样的错误。首先,我所做的是下载无头和普通的 HTML 源页面:

html = driver.page_source
file = open("foo.html","w")
file.write(html)
file.close()

无头模式的 HTML 源代码是一个短文件,几乎在末尾有这一行:The page cannot be displayed. Please contact the administrator for additional information. 但正常模式是预期的 HTML。

我通过添加一个用户代理解决了这个问题:

from fake_useragent import UserAgent
user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(executable_path = f"your_path",chrome_options=chrome_options)

【讨论】:

  • 大卫也是如此,我正在使用的网站最终阻止了无头 chrome 用户代理。为了让它在我的用例中正常工作,我不得不做一些补充:stackoverflow.com/a/69464060/1871891
【解决方案3】:

添加显式等待。您还应该使用另一个定位器,当前一个匹配 3 个元素。该元素具有唯一的 id 属性

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By

wait = WebDriverWait(self.driver, timeout)
data = wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]')))

【讨论】:

  • 我会尝试显式等待。在我尝试加载 url 后是否会出现显式等待?对于 ID 部分,我之所以远离它,是因为它往往会根据其位置而变化。 “t_trigger_TSLA”部分保持不变,但数字根据其排名而有所不同,这是我注意到的(也许我错了)。
  • @LuckyZakary 显式等待是针对特定定位器的,但您可以再次将wait 对象用于其他元素,只需更改定位器即可。如果 id 中的数字是动态的,您可以使用部分 id,我为此编辑了答案。
  • 我输入了您的代码,但仍然收到错误(我更新了帖子并将错误放在了底部)。我用 15 替换了 timeout 变量。我仍然认为问题出在驱动程序实际获取网站的那一行,因为打印出来的 html 仍然是空的。我认为这与无头运行有关,因为如果我只是删除无头选项,它就可以正常工作。
猜你喜欢
  • 2018-09-27
  • 2022-08-19
  • 2023-01-14
  • 2021-12-07
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
相关资源
最近更新 更多