天天看点

Python+Selenium浏览器自动化操作

作者:四川王大爷

1.安装selenium

pip install selenium # Windows
pip3 install selenium # Mac           

2.下载浏览器驱动

下载地址:https://chromedriver.chromium.org/downloads

Python+Selenium浏览器自动化操作

注意浏览器版本

将下载好的chromedriver_win32.zip解压得到一个chromedriver.exe文件,将其复制到你的Python程序执行路径。

Python+Selenium浏览器自动化操作

3.启动 Chrome浏览器的调试模式

  • 找到Chrome浏览器安装位置
Python+Selenium浏览器自动化操作
  • 执行以下命令
chrome.exe --remote-debugging-port=9222           
Python+Selenium浏览器自动化操作

4.示例代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

配置 = Options()
配置.debugger_address = 'localhost:9222'
驱动位置 = "./Data/chromedriver.exe" #我是把chromedriver驱动放在项目根目录下
浏览器 = webdriver.Chrome(驱动位置, chrome_options=配置)
print(浏览器.title)