python selenuim 唤起浏览器模拟浏览器搜索 chromedriver以及chrome浏览器闪退的情况处理

 安装 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值