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

Written by

in

文章目录
  • from selenium import webdriver from selenium.webdriver.chrome.service import Service # 指定浏览器和驱动的路径 chrome_path = r”C:Program FilesGoogleChromeApplicationchrome.exe” # 浏览器路径 driver_path = r”C:pathtochromedriver.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”)
  • from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService # 指定路径 chrome_binary_path = r”D:AnotherChromeApplicationchrome.exe” chromedriver_path = r”D:driverschromedriver.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”)
  • import os from selenium import webdriver from selenium.webdriver.chrome.service import Service def get_chrome_drivers(): “””获取系统中可能的Chrome浏览器路径””” possible_paths = [ r”C:Program FilesGoogleChromeApplicationchrome.exe”, r”C:Program Files (x86)GoogleChromeApplicationchrome.exe”, r”D:GoogleChromeApplicationchrome.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:pathtochromedriver.exe” # 对应的驱动路径 driver = open_specific_chrome(selected_browser, driver_path) driver.get(“https://www.baidu.com”)
  • 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:CustomChromeApplicationchrome.exe” driver_path = r”C:CustomDriverschromedriver.exe” profile_path = r”C:UsersYourNameAppDataLocalGoogleChromeUser DataProfile 1″ driver = open_chrome_with_profile(browser_path, driver_path, profile_path) driver.get(“https://www.example.com”)
  • 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 FilesGoogleChromeApplicationchrome.exe”, driver_path=r”C:webdriverschromedriver.exe”, options=custom_options ) driver.get(“https://www.baidu.com”) finally: manager.close()
  • 版本匹配:确保Chrome浏览器版本与chromedriver版本匹配 路径格式:使用原始字符串(r"path")或双反斜杠避免转义问题 权限:确保有足够的权限访问浏览器和驱动文件 杀毒软件:某些杀毒软件可能会阻止Selenium操作 选择适合你需求的方法,方法2是目前最推荐的方式,因为它使用了Selenium 4的最新语法。 到此这篇关于Python Selenium打开指定路径浏览器的几种实现方法的文章就介绍到这了,更多相关Python Selenium打开指定路径浏览器内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: Python Selenium无法打开Chrome浏览器处理自定义浏览器路径的问题及解决方法 python用selenium打开浏览器后秒关闭浏览器的解决办法 python使用selenium打开chrome浏览器时带用户登录信息实现过程详解 python selenium在打开的浏览器中动态调整User Agent python用selenium打开chrome浏览器保持登录方式
  • 目录
    • 方法1:使用 executable_path 参数(传统方式)
    • 方法2:使用 Service 类(推荐,Selenium 4+)
    • 方法3:自动检测多个浏览器版本
    • 方法4:处理用户数据目录
    • 方法5:完整的配置类
    • 注意事项:

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

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    
    # 指定浏览器和驱动的路径
    chrome_path = r"C:Program FilesGoogleChromeApplicationchrome.exe"  # 浏览器路径
    driver_path = r"C:pathtochromedriver.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")
    

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service as ChromeService
    
    # 指定路径
    chrome_binary_path = r"D:AnotherChromeApplicationchrome.exe"
    chromedriver_path = r"D:driverschromedriver.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")
    

    import os
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    
    def get_chrome_drivers():
        """获取系统中可能的Chrome浏览器路径"""
        possible_paths = [
            r"C:Program FilesGoogleChromeApplicationchrome.exe",
            r"C:Program Files (x86)GoogleChromeApplicationchrome.exe",
            r"D:GoogleChromeApplicationchrome.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:pathtochromedriver.exe"  # 对应的驱动路径
            
            driver = open_specific_chrome(selected_browser, driver_path)
            driver.get("https://www.baidu.com")
    

    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:CustomChromeApplicationchrome.exe"
    driver_path = r"C:CustomDriverschromedriver.exe"
    profile_path = r"C:UsersYourNameAppDataLocalGoogleChromeUser DataProfile 1"
    
    driver = open_chrome_with_profile(browser_path, driver_path, profile_path)
    driver.get("https://www.example.com")
    

    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 FilesGoogleChromeApplicationchrome.exe",
            driver_path=r"C:webdriverschromedriver.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 Selenium无法打开Chrome浏览器处理自定义浏览器路径的问题及解决方法
    • python用selenium打开浏览器后秒关闭浏览器的解决办法
    • python使用selenium打开chrome浏览器时带用户登录信息实现过程详解
    • python selenium在打开的浏览器中动态调整User Agent
    • python用selenium打开chrome浏览器保持登录方式

    站内搜索