安装 selenium
pip install selenium
安装chrome浏览器
查看chrome版本,并针对版本下载chrome driver
下载 chrome driver 驱动
下载地址:
找到对应的chrome版本进行下载|
https://googlechromelabs.github.io/chrome-for-testing/#canary (125版本之后)
https://chromedriver.storage.googleapis.com/index.html (125版本之前)
https://getwebdriver.com/chromedriver#stable (备用)注意区别:一个是是chrome 浏览器。一个是chrome驱动。
注意:以下浏览器的地址和驱动器的地址,要分别设置:
代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
try:
# 设置Chrome选项
chrome_options = Options()
chrome_options.add_argument("--start-maximized") # 启动最大化
chrome_options.add_argument("--disable-extensions") # 禁用扩展程序
chrome_options.add_argument("--disable-gpu") # 禁用GPU加速
# 指定Chrome浏览器路径
chrome_path = r'D:\software\chromedriver\chrome-win64\chrome-win64\chrome.exe' # 更新为您的Chrome浏览器路径
driver_path = r'D:\software\chromedriver\chromedriver127\chromedriver-win64\chromedriver.exe'
# 设置ChromeDriver路径并指定浏览器路径
service = Service(executable_path=driver_path)
chrome_options.binary_location = chrome_path
# 创建WebDriver实例
driver = webdriver.Chrome(service=service, options=chrome_options)
# 打开百度首页
driver.get("https://www.baidu.com")
# 打印当前页面标题
print(driver.title)
# 保持浏览器打开一段时间以便观察
time.sleep(10)
except Exception as e:
print(f"An error occurred: {e}")
finally:
# 关闭浏览器
driver.quit()
如果出现chrome浏览器闪退的情况,就使用 截图中的chrome浏览器和驱动器的下载,并在代码中指定路径位置即可。
如果不想设置浏览器的地址,就将浏览器的路径放入环境变量中,注意不要放chrome.exe,只要对应chrome.exe的父路径地址:
对应代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
try:
# 设置Chrome选项
chrome_options = Options()
chrome_options.add_argument("--start-maximized") # 启动最大化
chrome_options.add_argument("--disable-extensions") # 禁用扩展程序
chrome_options.add_argument("--disable-gpu") # 禁用GPU加速
# 设置ChromeDriver路径
driver_path = r'D:\software\chromedriver\chromedriver127\chromedriver-win64\chromedriver.exe' # 确保chromedriver在环境变量中
# 设置ChromeDriver服务
service = Service(executable_path=driver_path)
# 创建WebDriver实例
driver = webdriver.Chrome(service=service, options=chrome_options)
# 打开百度首页
driver.get("https://www.baidu.com")
# 打印当前页面标题
print(driver.title)
# 保持浏览器打开一段时间以便观察
time.sleep(10)
except Exception as e:
print(f"An error occurred: {e}")
finally:
# 关闭浏览器
driver.quit()