- 安装selenium
pip install selenium
- 浏览器驱动安装
wget https://github.com/mozilla/geckodriver/releases/download/v0.23.0/geckodriver-v0.23.0-linux64.tar.gz
tar -xvzf geckodriver-v0.23.0-linux64.tar.gz
chmod +x geckodriver
sudo mv geckodriver /usr/local/bin/
- 安装测试代码
from selenium import webdriver
import time
brower = webdriver.Firefox()
brower.get("http://www.baidu.com")
brower.find_element_by_id('kw').send_keys('selenium')
brower.find_element_by_id('su').click()
time.sleep(3)
print(brower.current_url)
brower.quit()
- 常见错误
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
表示geckodriver
没有安装成功。
也可以指定目录,例如指定在当前路径下。
brower = webdriver.Firefox(executable_path='./geckodriver')
- 无头参数
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time
options = Options()
options.add_argument('-headless') # 无头参数
brower = webdriver.Firefox(firefox_options=options)
brower.get("http://www.baidu.com")
brower.find_element_by_id('kw').send_keys('selenium')
brower.find_element_by_id('su').click()
time.sleep(3)
print(brower.current_url)
brower.quit()