Python Selenium:无法在浏览器无头模式下通过xpath找到元素

7
我正在尝试使用Python Selenium登录网站,以下是代码:
```python ```
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>

尝试使用 browser.find_element_by_link_text("Log In").click() - Andersson
同样的问题。在无头模式下不起作用,但在其他情况下可以正常工作。 - asheets
你能否更新问题并附上相关的_HTML_? - undetected Selenium
@DebanjanB 我已经包含了我想要交互的元素的HTML。当然,我提供的元素将不会有相同的xpath。 - asheets
5个回答

5

我遇到了同样的问题。解决办法是添加 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显示了"permission deny",于是我在Google上搜索了解决方案:如何通过无头驱动器访问网站而不被拒绝权限


2

我曾经遇到过这些工具版本的问题。我通过确保安装了最新版本的Chrome和webdriver来解决这个问题。也许这是一个类似的问题?!

但是,除此之外,您的选择器依赖于许多元素。因此,想象一下在无头模式下html看起来有点不同可能会导致您的问题。

我建议尝试使用更宽松的选择器,例如://a[starts-with(@href,'/member/general/login?')]

如果那样仍然不起作用,请尝试在无头模式下将html转储到文件中。只是为了看看无头浏览器看到了什么,并尝试用那个构建一个花哨的选择器。


2

我遇到了同样的问题。解决方案是提供窗口大小:

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

0

当我在我的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()

0

我曾经遇到过类似的问题,直到我意识到一些元素类会根据网站的主题而改变。在意识到这一点之前,我在页面处于暗模式时定义了我的CSS选择器和XPath。当运行无头浏览器时,页面会处于亮模式(通过保存截图得知)。我保存了整个HTML源代码,并在检查时发现一些类已更改,因此一些CSS选择器和XPath失败了。我所做的是创建一个单独的Chrome配置文件,并从该配置文件中将网站的主题更改为亮模式。然后我重新定义了我的CSS选择器和XPath,将此配置文件设置为我的机器人,一切都正常工作。

浏览器的默认主题可能会受到您系统的默认主题设置的影响。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接