簡體   English   中英

Python Selenium:瀏覽器無頭時無法通過xpath找到元素

[英]Python Selenium: Can't find element by xpath when browser is headless

我正在嘗試使用以下代碼使用 Python Selenium 登錄網站:

import time
from contextlib import contextmanager
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

@contextmanager
def getBrowser(*options):
    chrome_options = Options()
    if options: [chrome_options.add_argument(option) for option in options]
    browser = webdriver.Chrome(chrome_options=chrome_options)
    try:
        yield browser
    finally:
        browser.quit()


with getBrowser() as browser:
    browser.get('https://www.vinted.com/members/notifications')

    time.sleep(20)
    browser.find_element_by_xpath('//*[@id="content"]/div/div[2]/div/div/div[6]/div[3]/div[3]/a/span').click()

它工作得很好,但是當我向瀏覽器添加--headless選項時,它會引發NoSuchElementException

錯誤提升代碼:

with getBrowser('--headless') as browser:
    browser.get('https://www.vinted.com/members/notifications')

    time.sleep(20)
    browser.find_element_by_xpath('//*[@id="content"]/div/div[2]/div/div/div[6]/div[3]/div[3]/a/span').click()

追溯:

Traceback (most recent call last):

  File "<ipython-input-4-fe0834deb137>", line 1, in <module>
    runfile('C:/Users/Alec/vinted test case.py', wdir='C:/Users/Alec')

  File "C:\Users\Alec\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\Alec\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Alec/vinted test case.py", line 27, in <module>
    browser.find_element_by_xpath('//*[@id="content"]/div/div[2]/div/div/div[6]/div[3]/div[3]/a/span').click()

  File "C:\Users\Alec\selenium\webdriver\remote\webdriver.py", line 354, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)

  File "C:\Users\Alec\selenium\webdriver\remote\webdriver.py", line 832, in find_element
    'value': value})['value']

  File "C:\Users\Alec\selenium\webdriver\remote\webdriver.py", line 297, in execute
    self.error_handler.check_response(response)

  File "C:\Users\Alec\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="content"]/div/div[2]/div/div/div[6]/div[3]/div[3]/a/span"}
  (Session info: headless chrome=65.0.3325.181)
  (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64)

此錯誤僅在瀏覽器無頭時發生。 是什么導致了這種行為? 可以讓它在無頭模式下工作嗎?

目標 HTML:

<div class="u-flex-grow">
      <a class="c-button--inverse c-button--normal c-button--amplified c-button " href="/member/general/login?ref_url=%2Fmembers%2Fnotifications"><span class="c-button__content">Log In</span></a>
    </div>

我曾經在使用此類工具的版本時遇到過一些麻煩。 我通過確保安裝了最新版本的 Chrome 和 webdriver 來解決這個問題。 也許這是一個類似的問題?!

但除此之外,您的選擇器取決於很多元素。 因此,想象 html 在無頭模式下看起來有點不同可能會導致您的問題。

我會嘗試獲得一個不太嚴格的選擇器,如下所示: //a[starts-with(@href,'/member/general/login?')]

如果這不起作用,請嘗試從無頭模式中將 html 轉儲到文件中。 只是為了看看無頭瀏覽器看到了什么,並嘗試用它構建一個花哨的選擇器。

當我在 python 代碼中添加--headless時,我遇到了同樣的問題。 我使用ActionChains解決了它

from selenium.webdriver import ActionChains

text_list = browser.find_elements_by_xpath("//div[@class='tab-content']")
ActionChains(browser).click(text_list).perform()

我遇到過同樣的問題。 解決方案是提供窗口大小:

chrome_options.add_argument("--window-size=1920x1080")

我遇到過同樣的問題。 解決方案是添加 usr-agent:

user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
chrome_options.add_argument('user-agent={0}'.format(user_agent))

我通過打印頁面找到了原因

browser.get(url)
print(browser.page_source)

然后返回的 html 說權限拒絕,所以我用谷歌搜索。 遵循解決方案: 如何在不被拒絕許可的情況下通過無頭驅動程序訪問站點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM