我正在尝试 selenium 的Simple Usage。它的代码driver = webdriver.Firefox()
给出了错误。
这是我的完整代码:
while True:
try:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
except:
print('Failed to import selenium tools, retrying...')
continue
else:
print('Selenium import success!')
break
while True:
try:
browser = webdriver.Firefox()
except:
print('Open browser error: An error occured, retrying..')
continue
else:
print('Success!')
break
browser.get('http://www.python.org')
assert "Python" in browser.title
elem = browser.find_element_by_name('q')
elem.send_keys('pycon')
elem.send_keys(Keys.RETURN)
assert "No results found" not in browser.page_source
结果:
Selenium import success!
Open browser error: An error occured, retrying..Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
stdin=PIPE)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\code\python project\auto.py", line 14, in <module>
browser = webdriver.Firefox()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 160, in __init__
self.service.start()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\code\python project\auto.py", line 16, in <module>
print('Open browser error: An error occured, retrying..')
该Selenium import success!
结果表明,有在导入过程中没有问题。另一方面,browser = webdriver.Firefox()
是造成问题的原因。
我应该如何更改它以使其正常工作?注意:我正在处理的文件名为 auto.py
从这里下载 Windows 版本的 Geckodriver并将其放在方便的地方。然后在初始化browser
变量时,将完整路径传递给geckodriver.exe
像这样:
browser = webdriver.Firefox(executable_path='enter_path_here')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句