Install
- sudo apt install python3-pip
- pip3 install selenium
- wget https://github.com/mozilla/geckodriver/releases/download/v0.32.2/geckodriver-v0.32.2-linux64.tar.gz
- tar zxvf geckodriver-v0.32.2-linux64.tar.gz
- 解壓後有一個檔案 geckodriver 這是要給 selenium 執行 firefox 的必要檔案。
- sudo tar zxvf geckodriver-v0.32.2-linux64.tar.gz -C /usr/sbin
直接把 geckodriver 解壓到 /usr/sbin 就不用指定執行位置了。
Test
from selenium import webdriver
browser = webdriver.Firefox(executable_path="./geckodriver")
browser.get('https://trendoceans.com/blog')
print('Title: %s' % browser.title)
browser.quit()
- 執行 webdriver.Firefox() 時要指定 geckodriver 的位置,執行完後會跳出一個 firefox 視窗。
- 執行 browser.get() 後 firefox 視窗會載入網頁。
- 執行 browser.quit() 後會結束 firefox 視窗。
Debug
$ python3
Python 3.6.9 (default, Jan 26 2021, 15:33:00)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> browser = webdriver.Firefox()
Traceback (most recent call last):
File "/home/test/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start
stdin=PIPE)
File "/usr/lib/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver': 'geckodriver'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/test/.local/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 164, in __init__
self.service.start()
File "/home/test/.local/lib/python3.6/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.
Reference
留言
張貼留言