安装Chrome
apt-get update
apt-get install -f
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
dpkg -i google-chrome-stable_current_amd64.deb
检查Chrome版本
google-chrome --version
Google Chrome 113.0.5672.92
找到匹配的chromedriver
https://pypi.org/project/chromedriver-py/#history
pip install chromedriver-py==113.0.5672.63
验证
from selenium import webdriver
from time import sleep
from chromedriver_py import binary_path
options = webdriver.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome-stable' # 根据实际情况修改 Chrome 安装路径
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(executable_path=binary_path, options=options)
# 打开百度
driver.get('https://www.baidu.com')
# 输出页面源代码
print(driver.page_source)
# 搜索 Python
search_box = driver.find_element_by_id('kw')
search_box.send_keys('Python')
search_box.submit()
# 等待3秒
sleep(3)
# 输出搜索结果页的标题
print(driver.title)
# 关闭浏览器
driver.quit()
新版本selenium
from selenium import webdriver
from time import sleep
from chromedriver_py import binary_path
options = webdriver.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome-stable' # 根据实际情况修改 Chrome 安装路径
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(options=options)
# 打开百度
driver.get('https://www.baidu.com')
# 输出页面源代码
print(driver.page_source)
# 获取搜索框元素并搜索 Python
search_box = driver.find_element('css selector', '#kw') # 使用 css selector 查找元素
search_box.send_keys('Python')
search_box.submit()
# 等待3秒
sleep(3)
# 输出搜索结果页的标题
print(driver.title)
# 关闭浏览器
driver.quit()