带有pyvirtualdisplay的Selenium无法定位元素 [英] Selenium with pyvirtualdisplay unable to locate element
问题描述
我有一个使用 selenium 登录站点的工作脚本,如下所示:
I have a working script that logs into a site using selenium like this:
script.py
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
browser = webdriver.Firefox()
actions = webdriver.ActionChains(browser)
browser.get('some_url_I_need')
content = browser.find_element_by_id('content') # Error on this line
通过 ssh
在 amazon ubuntu box 上运行该脚本,我通过以下方式安装了 Firefox:sudo apt-get install firefox
running that script on an amazon ubuntu box through ssh
where I installed firefox the following way:
sudo apt-get install firefox
我得到的错误是:
selenium.common.exceptions.NoSuchElementException:消息:u'无法定位元素:{"method":"id","selector":"content"}'
selenium.common.exceptions.NoSuchElementException: Message: u'Unable to locate element: {"method":"id","selector":"content"}'
如果我也通过 ssh
在另一个 ubuntu 机器上运行相同的脚本,它运行良好,没有错误,但我不知道该机器上是如何安装 firefox 的,可能是什么原因那个错误.是否有相关的 firefox 安装以及如何正确安装它以与 pyvirtualdisplay 和 selenium 一起使用?
If I run the same script on another ubuntu box through ssh
too, it runs fine, no error, but I don't know how firefox was installed on that box, what could be the cause of that error. Is is related firefox installation and how to properly install it to be used with pyvirtualdisplay and selenium ?
推荐答案
如果网站上有一些动态内容需要等待一段时间直到您可以检索到所需的元素.尝试以下代码示例:
If there is some dynamic content on the website you need to wait some time until you can retrieve the wished element. Try to following code examples:
检查配置
您是否为
pyvirtualdisplay
安装了后端,例如xvfb
和xephyr
?如果没有,
Did you install a backend for
pyvirtualdisplay
likexvfb
andxephyr
? If not,
尝试:sudo apt-get install xvfb xserver-xephyr
第一次尝试:添加一个简单的time.sleep()
import time
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
browser = webdriver.Firefox()
actions = webdriver.ActionChains(browser)
browser.get('some_url_I_need')
time.sleep(5) # sleep for 5 seconds
content = browser.find_element_by_id('content') # Error on this line
第二次尝试:将 browser.implicitly_wait(30)
添加到您的 Selenium 网络驱动程序.
Second try: Add browser.implicitly_wait(30)
to your Selenium webdriver.
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
browser = webdriver.Firefox()
browser.implicitly_wait(30) # seconds
actions = webdriver.ActionChains(browser)
browser.get('some_url_I_need')
content = browser.find_element_by_id('content') # Error on this line
这篇关于带有pyvirtualdisplay的Selenium无法定位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!