python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Selenium打开指定路径浏览器

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

作者:冉成未来

文章介绍了在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打开指定路径浏览器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文