我正在尝试通过虚拟机运行一个简单的硒自动化脚本(它只是加载谷歌,搜索 youtube 并点击搜索按钮)。所以当我设置选项/参数时,如下面的代码所示(即使设置无头模式),这就是我所拥有的:#Beginning of code
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities.
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
display =Display(visible=0, size=(1024,768))
display.start()
options = Options()
options.headless = False
caps = DesiredCapabilities.FIREFOX
caps['marionette'] = False
binary = FirefoxBinary('/home/a-user/Al/firefox/firefox')
browser = webdriver.Firefox(firefox_binary= binary, options = options, capabilities= caps,executable_path=r"/home/a-user/Al/firefox/geckodriver")
browser.get('https://www.google.com')
browser.find_element_by_name('q').send_keys("Youtube")
browser.find_element_by_xpath('//[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
print("Headless Firefox Initialized")
browser.close()
display.stop()
#代码结束
但是当我尝试运行它时,它显示:
---错误消息的开头----
Traceback (most recent call last):
File "test.py", line 17, in <module>
browser.find_element_by_name('q').send_keys("Youtube")
File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 496, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"name","selector":"q"}
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_(file:///tmp/tmpG1qHlX/extensions/fxdriver@googlecode.com/components/driver-component.js:11885)
at FirefoxDriver.prototype.findElement (file:///tmp/tmpG1qHlX/extensions/fxdriver@googlecode.com/components/driver-component.js:11894)
at DelayedCommand.prototype.executeInternal_/k(file:///tmp/tmpG1qHlX/extensions/fxdriver@googlecode.com/components/command-processor.js:13395)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpG1qHlX/extensions/fxdriver@googlecode.com/components/command-processor.js:13400)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpG1qHlX/extensions/fxdriver@googlecode.com/components/command-processor.js:13342)
我想知道是否有任何方法可以确保页面正确加载,然后继续与元素进行自动交互。在此先感谢您的帮助!