硒仅在使用无头铬(Python)时无法定位元素 [英] Selenium Unable to locate element only when using headless chrome (Python)

查看:44
本文介绍了硒仅在使用无头铬(Python)时无法定位元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Selenium,需要使用云中的 jenkins 机器验证登录网页,该机器没有 GUI.我设法在具有 UI 的系统上成功运行该脚本.但是,当我修改脚本以无头运行时,它没有说无法定位元素.我的脚本如下:

I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element. My script is as follows:

#!/usr/bin/env python3

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')

driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)

lhip = '13.14.15.16'
user = 'username'
paswd = 'password'


parser = argparse.ArgumentParser()

parser.add_argument('-i', '--lh_ip',    type=str, metavar='', default=lhip,     help='Public IP of VM' )
parser.add_argument('-u', '--usr',      type=str, metavar='', default=user,     help='Username for VM')
parser.add_argument('-p', '--pwd',      type=str, metavar='', default=paswd,    help='Password for VM')

args = parser.parse_args()


lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
    if driver.title == 'Privacy error':
        driver.find_element_by_id('details-button').click()
        driver.find_element_by_id('proceed-link').click()
except:
    pass

driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
    if driver.find_element_by_tag_name('span'):
        print('Login Failed')
except:
    print('Login Successful')
driver.close()

python 脚本在没有 chrome_options 的情况下在我的系统上运行良好.但是,将它们添加为在无头模式下运行时,它会失败并显示以下输出:

The python script works fine on my system when used without the chrome_options. However upon adding them to run in headless mode, it fails with the following output:

[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
  File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
    driver.find_element_by_id('username').send_keys(args.usr)
  File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/ramesh/.local/lib/python3.6/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":"css selector","selector":"[id="username"]"}
  (Session info: headless chrome=85.0.4183.121)

由于我对 Selenium 进行了大约一天的学习,所以我可能会做一些相当愚蠢的事情,所以如果有人告诉我我做错了什么,我将非常感激.我在谷歌上搜索了很多东西,尝试了很多东西,但都没有奏效.还有为什么说css选择器"?当我只使用 id 作为用户名时?

Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked. Also why is it saying "css selector" when I have only used id for username?

推荐答案

如果脚本在没有无头模式的情况下运行良好,则可能是窗口大小有问题.在指定 --no-sandbox 选项的同时,尝试更改传递给 webdriver 的窗口大小

If the script is working perfectly fine without headless mode, probably there is issue with the window size. Along with specifying --no-sandbox option, try changing the window size passed to the webdriver

chrome_options.add_argument('--window-size=1920,1080')

chrome_options.add_argument('--window-size=1920,1080')

这个窗口大小适用于我的情况.

This window size worked in my case.

即使这不起作用,您也可能需要添加之前回答的等待计时器,因为与 UI 模式下的浏览器相比,无头模式下的渲染工作方式不同.

Even if this dosen't work you might need to add wait timers as answered before as rendering in headless mode works in a different way as compared to a browser in UI mode.

无头模式渲染参考 - https://www.toolsqa.com/selenium-webdriver/selenium-headless-browser-testing/

Ref for rendering in headless mode - https://www.toolsqa.com/selenium-webdriver/selenium-headless-browser-testing/

这篇关于硒仅在使用无头铬(Python)时无法定位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆