网上各种关于 py 的代码,但因为版本的不一样,环境的不一样,很有可能在 windows 下能跑的代码,在 mac 平台就跑不起来了,在selenium 4.0.0版本下,用selenium + pycharm 来抓取网页数据代码示例如下:
#导入 webdriver
from selenium import webdriver
#导入 Service
from selenium.webdriver.chrome.service import Service
#导入 Options
from selenium.webdriver.chrome.options import Options
# 配置 ChromeOptions
options = Options()
# 添加其他选项,如果需要的话
# options.add_argument("--headless") # 无界面模式
# 创建 ChromeDriver 服务,Service 要指定 chromedriver 的位置
service = Service('/Users/***/PycharmProjects/TDKproject/chromedriver')
# 创建浏览器驱动对象
driver = webdriver.Chrome(service=service, options=options)
# 打开网页
driver.get('https://www.baidu.com')
# 获取网页标题
title = driver.title
print(title)
运行代码出错提示找不到 chrome 的二进制文件:
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary
需要对 options.binary_location 的路径配置正确的 chrome 安装路径。如何查找路径?输入命令:
chrome://version/
在浏览器中查看到的命令行路径就是要赋值给 options.binary_location 的路径
代码如下:
#通过 options.binary_location设置chrome 的安装位置
options.binary_location = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
测试通过