Python Selenium打开指定路径浏览器的几种实现方法

 更新时间:2025年11月17日 08:59:28   作者:冉成未来  
文章介绍了在PythonSelenium中打开谷歌浏览器的几种方法,并推荐使用Service类(方法2),因为它是Selenium4的推荐方式,语法更为简洁,同时,文章还提醒了版本匹配、路径格式、权限和杀毒软件等注意事项,需要的朋友可以参考下

在Python Selenium中打开指定路径的谷歌浏览器和驱动,有几种方法可以实现:

方法1:使用 executable_path 参数(传统方式)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 指定浏览器和驱动的路径
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"  # 浏览器路径
driver_path = r"C:\path\to\chromedriver.exe"  # 驱动路径

# 配置浏览器选项
options = webdriver.ChromeOptions()
options.binary_location = chrome_path  # 指定浏览器可执行文件路径

# 创建驱动服务
service = Service(executable_path=driver_path)

# 启动浏览器
driver = webdriver.Chrome(service=service, options=options)

# 使用浏览器
driver.get("https://www.baidu.com")

方法2:使用 Service 类(推荐,Selenium 4+)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService

# 指定路径
chrome_binary_path = r"D:\AnotherChrome\Application\chrome.exe"
chromedriver_path = r"D:\drivers\chromedriver.exe"

# 配置选项
options = webdriver.ChromeOptions()
options.binary_location = chrome_binary_path

# 创建服务并启动
service = ChromeService(executable_path=chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)

driver.get("https://www.example.com")

方法3:自动检测多个浏览器版本

import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def get_chrome_drivers():
    """获取系统中可能的Chrome浏览器路径"""
    possible_paths = [
        r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
        r"D:\Google\Chrome\Application\chrome.exe",
        # 添加其他可能的路径
    ]
    
    existing_browsers = []
    for path in possible_paths:
        if os.path.exists(path):
            existing_browsers.append(path)
    
    return existing_browsers

def open_specific_chrome(browser_path, driver_path):
    """打开指定路径的Chrome浏览器"""
    options = webdriver.ChromeOptions()
    options.binary_location = browser_path
    
    service = Service(executable_path=driver_path)
    driver = webdriver.Chrome(service=service, options=options)
    
    return driver

# 使用示例
if __name__ == "__main__":
    # 显示所有可用的Chrome浏览器
    browsers = get_chrome_drivers()
    print("找到的Chrome浏览器:")
    for i, browser in enumerate(browsers):
        print(f"{i+1}. {browser}")
    
    # 选择要使用的浏览器
    if browsers:
        # 使用第一个找到的浏览器,或者你可以让用户选择
        selected_browser = browsers[0]
        driver_path = r"C:\path\to\chromedriver.exe"  # 对应的驱动路径
        
        driver = open_specific_chrome(selected_browser, driver_path)
        driver.get("https://www.baidu.com")

方法4:处理用户数据目录

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def open_chrome_with_profile(browser_path, driver_path, profile_path=None):
    """打开指定浏览器并可选地使用特定用户配置文件"""
    
    options = webdriver.ChromeOptions()
    options.binary_location = browser_path
    
    # 如果需要使用特定的用户配置文件
    if profile_path:
        options.add_argument(f"--user-data-dir={profile_path}")
    
    # 其他常用选项
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    
    service = Service(executable_path=driver_path)
    driver = webdriver.Chrome(service=service, options=options)
    
    # 隐藏webdriver属性
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    
    return driver

# 使用示例
browser_path = r"C:\Custom\Chrome\Application\chrome.exe"
driver_path = r"C:\Custom\Drivers\chromedriver.exe"
profile_path = r"C:\Users\YourName\AppData\Local\Google\Chrome\User Data\Profile 1"

driver = open_chrome_with_profile(browser_path, driver_path, profile_path)
driver.get("https://www.example.com")

方法5:完整的配置类

import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

class ChromeManager:
    def __init__(self):
        self.driver = None
    
    def start_chrome(self, browser_path, driver_path, options=None):
        """启动指定路径的Chrome浏览器"""
        
        if not os.path.exists(browser_path):
            raise FileNotFoundError(f"Chrome浏览器未找到: {browser_path}")
        
        if not os.path.exists(driver_path):
            raise FileNotFoundError(f"Chrome驱动未找到: {driver_path}")
        
        # 创建选项
        chrome_options = webdriver.ChromeOptions()
        chrome_options.binary_location = browser_path
        
        # 添加自定义选项
        if options:
            for option in options:
                chrome_options.add_argument(option)
        
        # 创建服务
        service = Service(executable_path=driver_path)
        
        # 启动浏览器
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        return self.driver
    
    def close(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()

# 使用示例
manager = ChromeManager()

# 配置选项
custom_options = [
    "--disable-extensions",
    "--no-sandbox",
    "--disable-dev-shm-usage",
    "--start-maximized"
]

try:
    driver = manager.start_chrome(
        browser_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        driver_path=r"C:\webdrivers\chromedriver.exe",
        options=custom_options
    )
    
    driver.get("https://www.baidu.com")
    
finally:
    manager.close()

注意事项:

  1. 版本匹配:确保Chrome浏览器版本与chromedriver版本匹配
  2. 路径格式:使用原始字符串(r"path")或双反斜杠避免转义问题
  3. 权限:确保有足够的权限访问浏览器和驱动文件
  4. 杀毒软件:某些杀毒软件可能会阻止Selenium操作

选择适合你需求的方法,方法2是目前最推荐的方式,因为它使用了Selenium 4的最新语法。

到此这篇关于Python Selenium打开指定路径浏览器的几种实现方法的文章就介绍到这了,更多相关Python Selenium打开指定路径浏览器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python爬虫控制aiohttp并发数量方式

    python爬虫控制aiohttp并发数量方式

    这篇文章主要介绍了python爬虫控制aiohttp并发数量方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • python多线程socket编程之多客户端接入

    python多线程socket编程之多客户端接入

    这篇文章主要为大家详细介绍了python多线程socket编程之多客户端接入,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • Django批量覆盖更新实现示例

    Django批量覆盖更新实现示例

    这篇文章主要为大家介绍了Django批量覆盖更新实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Python MySQLdb 执行sql语句时的参数传递方式

    Python MySQLdb 执行sql语句时的参数传递方式

    这篇文章主要介绍了Python MySQLdb 执行sql语句时的参数传递方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析

    Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析

    这篇文章主要给大家介绍了关于Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧
    2018-05-05
  • Python数据可视化实现多种图例代码详解

    Python数据可视化实现多种图例代码详解

    这篇文章主要介绍了Python数据可视化实现多种图例代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Python中使用logging模块打印log日志详解

    Python中使用logging模块打印log日志详解

    这篇文章主要介绍了Python中使用logging模块打印log日志详解,本文讲解了logging模块介绍、基本使用方法、高级使用方法、使用实例等,需要的朋友可以参考下
    2015-04-04
  • Django中文件上传和文件访问微项目的方法

    Django中文件上传和文件访问微项目的方法

    这篇文章主要介绍了Django中文件上传和文件访问微项目的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • 学习python 的while循环嵌套

    学习python 的while循环嵌套

    这篇文章主要为大家介绍了python 的while循环嵌套,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-12-12
  • Python re.split方法分割字符串的实现示例

    Python re.split方法分割字符串的实现示例

    本文主要介绍了Python re.split方法分割字符串的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08

最新评论