Webdriver_01

本文介绍使用Selenium WebDriver进行网页自动化测试的方法,包括浏览器控制、元素操作、鼠标事件处理及警告框交互等内容。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Commend {
    public static void main(String [] args){
        //设置浏览器驱动
        WebDriver driver=new ChromeDriver();
        /**
         * sendKeys——模拟输入操作
         * clear——清除文本
         * click——点击操作,可以点击任何可点击的元素,操作面比较广
         * submit——表单提交操作,某种程度和click作用一样,但是操作范围较小
         * getAttribute——获取元素属性值,如id,class,name
         * isDisplayed——判断元素是否为用户可见 */
        driver.get("https://www.baidu.com");
        //清除操作+输入操作
        driver.findElement(By.id("kw")).sendKeys("java");
        driver.findElement(By.id("kw")).clear();
        //点击操作
        driver.findElement(By.id("kw")).sendKeys("java selenium");
        driver.findElement(By.id("su")).click();

        //提交操作:submit
        driver.get("https://www.baidu.com");
        driver.findElement(By.id("kw")).sendKeys("java");
        driver.findElement(By.id("su")).submit();
        System.out.println(driver.findElement(By.id("su")).getAttribute("value"));

        //获取百度输入框的尺寸
        driver.get("https://www.baidu.com");
        driver.findElement(By.id("kw")).getSize();
        System.out.println(driver.findElement(By.id("kw")).getSize());

        //获取百度按钮中的文本
        driver.get("https://www.baidu.com");
        WebElement text=driver.findElement(By.id("cp"));
        System.out.println(text.getText());
       System.out.println(text.getAttribute("id"));

       //设置元素是否为用户可见
        driver.get("https://www.baidu.com");
        WebElement sub=driver.findElement(By.id("su"));
        System.out.println(sub.isDisplayed());

        //关闭浏览器
        driver.quit();



    }
}
1.控制浏览器

方法:

driver.manage().window().setSize(new Dimension(468,900));---设置窗口大小
driver.manage().window().maximize();----窗口最大化
driver.navigate().back();——后退
driver.navigate().forward();——前进
driver.navigate().refresh();——刷新当前页面
driver.getCurrentUrl()——获取当前页面的URL
2.简单元素操作
clear——清除文本
click——点击元素,可以点击任何可以点击的元素,操作面比较大
sendkeys——模拟元素输入
submit——表达提交操作,某种情况下可以等同click,但是操作面较小
getsize——获取尺寸
getText——获取文本,一般断言用的比较多
getAttribute("id")——id就是所要获取到的属性是id的值,也可以修改为value,class,name,等属性
isDisplayed——判断元素是否为用户可见

3.鼠标事件
鼠标事件存储在Actions包内,需要导入该包,且需要new Actinons(driver)将驱动传入;
contextClick ( )  右击
clickAndHold() 鼠标点击并控制
doubleClick()双击
dragAndDrop() 拖动
release()释放鼠标
perform()执行所有Actions中存储的行为







select下拉选择标签
selectByValue





警告框如何处理(警告框一般无法通过前端工具定位到),如下


警告框处理(就是使用前端无法定位的)
switchTo().alert()获取警告框
&accept()接受现有的警告框
&dismiss()解散现有的警告框
&getText()获取警告框的文本信息
&sendKeys(keysSend)发送文本至警告框
& keysSend将文本发送至警告框

















Keys键盘操作
BACK_SPACE——删除
SPACE——空格
CONTROL——ctral,后面可加a组合成ctrl+a,ctrl+v,ctrl+z等
ENTER——回车键


获取验证信息
getTitle() 获取页面title
getCurrentUrl)() 获取当前页面url
getText() 获取页面文本信息

设置等待时长










  • 有硬性等待 Thread.sleep(1000)——缺点浪费时间
  • 显示等待,等待某个元素,需要导入WebDriverWait包,并传入3个参数(driver,最大等待时长,每个多长时间检测一次
  • 隐式等待
  • 另外也可以自己定义一个等待时间































                
<think> ### Chrome版本获取失败的终极解决方案 该错误表明您的系统无法通过WMIC命令获取Chrome版本。我将提供一个更强大、完全跨平台且不依赖WMIC的Chrome版本获取方法,并重构整个驱动管理系统。 #### 改进的跨平台Chrome版本获取与驱动管理 ```python import os import sys import platform import json import re import subprocess import requests import zipfile import tarfile import time from pathlib import Path from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from packaging import version # 日志配置(简化为标准输出) def log(level, message): timestamp = time.strftime("%Y-%m-%d %H:%M:%S") print(f"{timestamp} | {level} | {message}") class RobustChromeDriverManager: """健壮的Chrome驱动管理器,解决所有版本获取问题""" def __init__(self): self.system_platform = platform.system().lower() self.arch = platform.machine().lower() self.chrome_version = self._get_chrome_version_without_wmic() self.driver_dir = self._get_driver_directory() self.driver_path = None def _get_driver_directory(self): """获取驱动存储目录""" if self.system_platform == "windows": base_dir = Path.home() / "AppData" / "Local" / "ChromeDriver" elif self.system_platform == "darwin": base_dir = Path.home() / "Library" / "Application Support" / "ChromeDriver" else: # linux base_dir = Path.home() / ".local" / "bin" / "chromedriver" base_dir.mkdir(parents=True, exist_ok=True) return base_dir def _get_chrome_version_without_wmic(self): """不依赖WMIC的Chrome版本获取方法""" try: # Windows系统:通过注册表获取 if self.system_platform == "windows": try: # 方法1: 通过注册表查询 import winreg key_path = r"SOFTWARE\Google\Chrome\BLBeacon" with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key: version, _ = winreg.QueryValueEx(key, "version") return version.split('.')[0] except ImportError: # 方法2: 通过文件元数据获取 chrome_paths = [ Path(os.environ.get('PROGRAMFILES', 'C:\\Program Files')) / 'Google' / 'Chrome' / 'Application' / 'chrome.exe', Path(os.environ.get('PROGRAMFILES(X86)', 'C:\\Program Files (x86)')) / 'Google' / 'Chrome' / 'Application' / 'chrome.exe', Path.home() / 'AppData' / 'Local' / 'Google' / 'Chrome' / 'Application' / 'chrome.exe' ] for path in chrome_paths: if path.exists(): # 使用PowerShell获取文件版本 ps_command = f'(Get-Item "{path}").VersionInfo.FileVersion' version = subprocess.check_output(['powershell', '-Command', ps_command], encoding='utf-8').strip() if version: return version.split('.')[0] # macOS系统 elif self.system_platform == "darwin": # 尝试通过应用程序包获取 plist_path = "/Applications/Google Chrome.app/Contents/Info.plist" if Path(plist_path).exists(): # 使用plutil工具解析plist cmd = f"plutil -extract CFBundleShortVersionString xml1 -o - '{plist_path}'" output = subprocess.check_output(cmd, shell=True, encoding='utf-8') # 提取版本号 match = re.search(r'<string>(\d+\.\d+\.\d+\.\d+)</string>', output) if match: return match.group(1).split('.')[0] # 通过命令行获取 cmd = "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version" output = subprocess.check_output(cmd, shell=True, encoding='utf-8') return output.split()[2].split('.')[0] # Linux系统 else: # 尝试多种命令 commands = [ "google-chrome --version", "google-chrome-stable --version", "chromium-browser --version", "chromium --version" ] for cmd in commands: try: output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, encoding='utf-8') # 提取版本号 match = re.search(r'\d+\.\d+\.\d+', output) if match: return match.group(0).split('.')[0] except: continue # 尝试通过配置文件获取 config_path = Path.home() / '.config' / 'google-chrome' / 'Last Version' if config_path.exists(): with open(config_path, 'r') as f: return f.read().strip().split('.')[0] except Exception as e: log('ERROR', f"获取Chrome版本失败: {str(e)}") return None def _get_driver_download_url(self, chrome_version=None): """构建驱动下载URL(支持直接指定版本)""" chrome_version = chrome_version or self.chrome_version if not chrome_version: return None base_url = "https://chromedriver.storage.googleapis.com" # 检测架构 is_arm = "arm" in self.arch or "aarch" in self.arch platform_key = { "windows": "win32", "darwin": "mac_arm64" if is_arm else "mac64", "linux": "linux64" }.get(self.system_platform, "win32") return f"{base_url}/{chrome_version}/chromedriver_{platform_key}.zip" def _download_driver(self, url): """下载驱动并返回路径""" try: log('INFO', f"下载驱动: {url}") response = requests.get(url, stream=True, timeout=30) # 保存压缩包 ext = ".zip" if url.endswith('.zip') else ".tar.gz" archive_path = self.driver_dir / f"chromedriver{ext}" with open(archive_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) # 解压 extract_path = self.driver_dir if archive_path.suffix == '.zip': with zipfile.ZipFile(archive_path, 'r') as zip_ref: zip_ref.extractall(extract_path) else: with tarfile.open(archive_path, 'r:gz') as tar_ref: tar_ref.extractall(extract_path) # 删除压缩包 archive_path.unlink() # 查找驱动文件 driver_name = "chromedriver.exe" if self.system_platform == "windows" else "chromedriver" for file in extract_path.rglob(driver_name): self.driver_path = file break if not self.driver_path: raise FileNotFoundError("解压后未找到驱动文件") # 设置权限(非Windows) if self.system_platform != "windows": self.driver_path.chmod(0o755) log('SUCCESS', f"驱动安装成功: {self.driver_path}") return self.driver_path except Exception as e: log('ERROR', f"驱动下载失败: {str(e)}") return None def get_driver_path(self): """获取驱动路径,包含多重回退机制""" # 方法1: 使用webdriver_manager try: driver_path = ChromeDriverManager().install() if driver_path and Path(driver_path).exists(): log('SUCCESS', f"通过webdriver_manager获取驱动: {driver_path}") return driver_path except Exception as e: log('WARNING', f"webdriver_manager失败: {str(e)}") # 方法2: 检查系统路径 try: driver_name = "chromedriver.exe" if self.system_platform == "windows" else "chromedriver" which_cmd = "where" if self.system_platform == "windows" else "which" output = subprocess.check_output(f"{which_cmd} {driver_name}", shell=True, encoding='utf-8', stderr=subprocess.DEVNULL) paths = output.strip().splitlines() for path in paths: if Path(path).exists(): log('SUCCESS', f"在系统路径中找到驱动: {path}") return path except: pass # 方法3: 使用已知的Chrome版本下载 if self.chrome_version: url = self._get_driver_download_url() driver_path = self._download_driver(url) if driver_path: return driver_path # 方法4: 获取最新的稳定版本 try: latest_release_url = "https://chromedriver.storage.googleapis.com/LATEST_RELEASE" latest_version = requests.get(latest_release_url, timeout=10).text.strip() url = self._get_driver_download_url(latest_version) driver_path = self._download_driver(url) if driver_path: return driver_path except: log('ERROR', "无法获取最新驱动版本") # 方法5: 使用固定版本作为最后手段 fallback_version = "114.0.5735.90" # 一个广泛兼容的版本 log('WARNING', f"使用回退驱动版本: {fallback_version}") url = self._get_driver_download_url(fallback_version) driver_path = self._download_driver(url) if driver_path: return driver_path log('ERROR', "所有驱动获取方法均失败") return None def create_webdriver(): """创建WebDriver实例""" # 配置选项 options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-gpu") options.add_argument("--log-level=3") # 无头模式(如果不在桌面环境) if not sys.platform.lower().startswith('win') and "DISPLAY" not in os.environ: options.add_argument("--headless=new") # 初始化驱动管理器 driver_manager = RobustChromeDriverManager() driver_path = driver_manager.get_driver_path() if not driver_path: raise RuntimeError("无法获取ChromeDriver路径") # 创建服务 service = Service(executable_path=str(driver_path)) # 尝试启动浏览器 try: driver = webdriver.Chrome(service=service, options=options) # 验证驱动可用 driver.get("https://www.google.com") if "Google" not in driver.title: driver.quit() raise RuntimeError("驱动验证失败") return driver except Exception as e: # 尝试无路径方式(某些环境可能不需要显式路径) try: log('WARNING', "显式路径启动失败,尝试自动发现") driver = webdriver.Chrome(options=options) return driver except: raise RuntimeError(f"启动Chrome失败: {str(e)}") # 使用示例 if __name__ == "__main__": try: driver = create_webdriver() print("浏览器启动成功!") driver.quit() except Exception as e: print(f"启动失败: {str(e)}") sys.exit(1) ``` ### 改进方案核心亮点 #### 1. 完全绕过WMIC的版本获取 - **Windows系统**: 1. 优先使用注册表查询 (HKCU\Software\Google\Chrome\BLBeacon) 2. 使用PowerShell获取文件版本信息 3. 扫描多个可能安装路径 - **macOS系统**: 1. 解析应用程序的Info.plist文件 2. 通过命令行直接获取版本 - **Linux系统**: 1. 多种命令尝试 (`google-chrome --version`, `chromium-browser --version`) 2. 读取用户配置目录中的版本缓存 #### 2. 五级驱动获取回退机制 1. **webdriver_manager** - 首选自动管理 2. **系统PATH查找** - 查找预安装驱动 3. **精确版本下载** - 根据获取到的Chrome版本 4. **最新稳定版** - 当无法获取版本时下载最新版 5. **固定回退版本** - 使用兼容性良好的114版本作为最后手段 #### 3. 增强的错误处理 - 每个步骤都有独立异常捕获 - 详细日志记录各阶段状态 - 驱动下载超时控制(30秒) - 驱动安装后自动验证 #### 4. 跨平台兼容性 - 支持Windows/macOS/Linux主流系统 - 自动区分ARM架构 - 正确处理Unix文件权限 - 自适应无头环境 ### 针对特定错误的解决方案 #### 1. 解决WMIC错误2147749911 此错误通常由权限问题或WMIC服务不可用导致。改进方案完全避免使用WMIC,采用注册表和PowerShell替代。 #### 2. 解决中文系统乱码问题 在Windows系统上,我们使用UTF-8编码显式指定: ```python # 在调用subprocess时添加 output = subprocess.check_output(cmd, encoding='utf-8') ``` #### 3. 解决驱动下载超时问题 添加显式超时设置: ```python response = requests.get(url, stream=True, timeout=30) ``` ### 替代方案:使用Chromium嵌入式驱动 如果上述方案仍然无效,可以使用Chrome的备用方案: ```python from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.core.os_manager import ChromeType from webdriver_manager.chrome import ChromeDriverManager def create_chromium_driver(): options = Options() options.add_argument("--headless=new") # 使用Chromium浏览器 driver = webdriver.Chrome( service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options ) return driver ``` §§相关问题§§: 1. 如何在企业防火墙后设置Selenium驱动自动下载? 2. 如何实现Selenium Grid分布式测试环境的驱动管理? 3. 通过Docker运行Selenium时如何优化Chrome启动参数? 4. 如何彻底避免ChromeDriver与Chrome浏览器版本不匹配问题? </think> ### 终极解决方案:绕过 Chrome 版本检测的 Chromedriver 管理 针对 WMIC 命令失败和版本检测问题,我将提供一个完全不依赖 Chrome 版本检测的解决方案,同时解决中文系统乱码问题。 #### 完整解决方案(跨平台,无需 Chrome 版本检测) ```python import os import sys import platform import subprocess import requests import zipfile import tarfile import stat import time from pathlib import Path from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from packaging import version # 增强日志函数(解决中文乱码) def log(level, message): timestamp = time.strftime("%Y-%m-%d %H:%M:%S") # 确保在Windows上使用正确的编码 if sys.platform == "win32": try: sys.stdout.buffer.write(f"{timestamp} | {level} | {message}\n".encode('utf-8')) sys.stdout.flush() except: print(f"{timestamp} | {level} | {message}") else: print(f"{timestamp} | {level} | {message}") class UniversalDriverManager: """通用驱动管理器 - 完全不依赖本地Chrome版本检测""" def __init__(self): self.system_platform = platform.system().lower() self.arch = platform.machine().lower() self.driver_dir = self._get_driver_directory() self.driver_path = None def _get_driver_directory(self): """获取安全的驱动存储目录""" if self.system_platform == "windows": base_dir = Path.home() / "AppData" / "Local" / "ChromeDriverBin" elif self.system_platform == "darwin": base_dir = Path.home() / "Library" / "ChromeDriver" else: # linux base_dir = Path.home() / ".cache" / "chromedriver" base_dir.mkdir(parents=True, exist_ok=True) return base_dir def resolve_platform_key(self): """解析平台标识符(完全不依赖Chrome版本)""" # 检测是否为ARM架构 is_arm = "arm" in self.arch or "aarch" in self.arch if self.system_platform == "windows": return "win32" elif self.system_platform == "darwin": return "mac_arm64" if is_arm else "mac64" else: # linux return "linux64" def get_latest_compatible_version(self): """获取最新兼容版本(绕过本地Chrome检测)""" try: # 获取Chromedriver的所有版本 response = requests.get("https://chromedriver.storage.googleapis.com", timeout=10) if response.status_code != 200: return None # 解析XML响应 from xml.etree import ElementTree as ET root = ET.fromstring(response.content) # 提取所有版本号 versions = [] for content in root.findall(".//{http://doc.s3.amazonaws.com/2006-03-01}Contents"): key = content.find("{http://doc.s3.amazonaws.com/2006-03-01}Key").text if key.endswith(f"chromedriver_{self.resolve_platform_key()}.zip"): version = key.split('/')[0] try: versions.append(version.parse(version)) except: continue # 返回最新版本 if versions: return str(max(versions)) return None except: return None def download_driver(self, chrome_version=None): """下载驱动并返回路径(不依赖本地Chrome版本)""" try: # 确定要下载的版本 target_version = chrome_version or self.get_latest_compatible_version() or "LATEST_RELEASE" # 构建下载URL base_url = "https://chromedriver.storage.googleapis.com" platform_key = self.resolve_platform_key() url = f"{base_url}/{target_version}/chromedriver_{platform_key}.zip" log("INFO", f"下载驱动: {url}") response = requests.get(url, stream=True, timeout=30) # 保存压缩包 ext = ".zip" if self.system_platform == "windows" else ".tar.gz" archive_path = self.driver_dir / f"chromedriver{ext}" with open(archive_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) # 解压 extract_path = self.driver_dir if archive_path.suffix == '.zip': with zipfile.ZipFile(archive_path, 'r') as zip_ref: zip_ref.extractall(extract_path) else: with tarfile.open(archive_path, 'r:gz') as tar_ref: tar_ref.extractall(extract_path) # 删除压缩包 archive_path.unlink() # 查找驱动文件 driver_name = "chromedriver.exe" if self.system_platform == "windows" else "chromedriver" self.driver_path = next(extract_path.rglob(driver_name), None) if not self.driver_path: raise FileNotFoundError("解压后未找到驱动文件") # 设置权限(非Windows) if self.system_platform != "windows": self.driver_path.chmod(self.driver_path.stat().st_mode | stat.S_IEXEC) log("SUCCESS", f"驱动安装成功: {self.driver_path}") return self.driver_path except Exception as e: log("ERROR", f"驱动下载失败: {type(e).__name__} - {str(e)}") return None def get_driver_path(self): """获取驱动路径(多重回退机制)""" # 方法1: 使用webdriver_manager(自动模式) try: driver_path = ChromeDriverManager().install() if driver_path and Path(driver_path).exists(): log("SUCCESS", f"通过webdriver_manager获取驱动: {driver_path}") return driver_path except Exception as e: log("WARNING", f"webdriver_manager失败: {type(e).__name__} - {str(e)}") # 方法2: 尝试下载最新兼容版本 driver_path = self.download_driver() if driver_path: return driver_path # 方法3: 使用固定版本回退 log("WARNING", "尝试使用固定版本回退方案") fixed_versions = ["114.0.5735.90", "115.0.5790.170", "120.0.6099.109"] for ver in fixed_versions: driver_path = self.download_driver(ver) if driver_path: log("SUCCESS", f"使用固定版本成功: {ver}") return driver_path # 终极回退:尝试系统默认路径 log("WARNING", "尝试系统默认路径查找") driver_name = "chromedriver.exe" if self.system_platform == "windows" else "chromedriver" default_paths = [ self.driver_dir / driver_name, Path("/usr/local/bin") / driver_name, Path("/usr/bin") / driver_name, Path.cwd() / driver_name ] for path in default_paths: if path.exists(): log("SUCCESS", f"在默认路径找到驱动: {path}") return path log("ERROR", "所有驱动获取方法均失败") return None def create_webdriver(): """创建WebDriver实例(完全绕过版本检测)""" # 配置选项 options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-gpu") # 禁用不必要的日志 options.add_experimental_option('excludeSwitches', ['enable-logging']) # 无头模式检测 if not sys.platform.lower().startswith('win') and "DISPLAY" not in os.environ: options.add_argument("--headless=new") # 初始化驱动管理器 driver_manager = UniversalDriverManager() driver_path = driver_manager.get_driver_path() if not driver_path: raise RuntimeError("无法获取ChromeDriver路径") # 创建服务 service = Service(executable_path=str(driver_path)) # 尝试启动浏览器 try: log("INFO", "尝试启动Chrome浏览器...") driver = webdriver.Chrome(service=service, options=options) log("SUCCESS", "浏览器启动成功") return driver except Exception as e: # 绕过服务直接启动 try: log("WARNING", f"使用Service启动失败: {str(e)},尝试直接启动") driver = webdriver.Chrome(options=options) log("SUCCESS", "直接启动浏览器成功") return driver except: raise RuntimeError(f"所有启动方式均失败: {str(e)}") # 使用示例(解决中文Windows编码问题) if __name__ == "__main__": # Windows系统编码修复 if sys.platform == "win32": sys.stdout.reconfigure(encoding='utf-8') try: driver = create_webdriver() log("SUCCESS", "执行测试导航...") driver.get("https://www.baidu.com") log("SUCCESS", f"页面标题: {driver.title}") driver.quit() except Exception as e: log("ERROR", f"程序执行失败: {type(e).__name__} - {str(e)}") sys.exit(1) ``` ### 解决方案核心亮点 #### 1. 完全绕过 Chrome 版本检测 - **XML API 解析**:直接查询 Chromedriver 存储服务器获取最新版本 - **平台自动识别**:独立于 Chrome 安装状态检测系统平台 - **固定版本回退**:使用广泛兼容的 114/115/120 版本作为备选方案 #### 2. Windows 系统增强修复 1. **中文乱码解决方案**: ```python if sys.platform == "win32": sys.stdout.reconfigure(encoding='utf-8') ``` 2. **WMIC 替代方案**: - 完全移除所有 WMIC 依赖 - 使用跨平台的文件操作和 HTTP 请求 3. **权限问题处理**: - 使用用户目录存储驱动(避免 Program Files 权限问题) - 自动构建安全路径:`%USERPROFILE%\AppData\Local\ChromeDriverBin` #### 3. 增强的错误处理机制 - **五级回退策略**: 1. 使用 webdriver_manager 2. 下载最新兼容版本 3. 尝试固定版本(114/115/120) 4. 搜索默认路径 5. 绕过 Service 直接启动 - **详细错误日志**: ```python log("ERROR", f"驱动下载失败: {type(e).__name__} - {str(e)}") ``` #### 4. 跨平台兼容性增强 - **统一压缩包处理**: ```python if archive_path.suffix == '.zip': # ZIP处理 else: # TAR.GZ处理 ``` - **权限自动设置**: ```python self.driver_path.chmod(self.driver_path.stat().st_mode | stat.S_IEXEC) ``` ### 替代方案:使用独立 Chrome 实例 如果上述方案仍不工作,可以使用完全独立的 Chrome 实例(不需要本地 Chrome): ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options def create_standalone_chrome(): """使用独立捆绑的Chrome实例""" options = Options() # 配置独立Chrome路径 if sys.platform == "win32": options.binary_location = r"C:\Path\To\PortableChrome\chrome.exe" elif sys.platform == "darwin": options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" else: options.binary_location = "/opt/google/chrome/chrome" # 自动下载驱动配置... return webdriver.Chrome(options=options) ``` ### Windows 专用修复脚本 如果您只需要在 Windows 系统运行,可以使用这个 PowerShell 一键修复脚本: ```powershell # 保存为 fix_chromedriver.ps1 $ErrorActionPreference = "Stop" # 创建驱动目录 $driverDir = Join-Path $env:LOCALAPPDATA "ChromeDriverBin" if (-not (Test-Path $driverDir)) { New-Item -ItemType Directory -Path $driverDir | Out-Null } # 下载最新Chromedriver $latestUrl = "https://chromedriver.storage.googleapis.com/LATEST_RELEASE" $latestVersion = (Invoke-WebRequest -Uri $latestUrl -UseBasicParsing).Content.Trim() $downloadUrl = "https://chromedriver.storage.googleapis.com/$latestVersion/chromedriver_win32.zip" Write-Host "下载Chromedriver: $downloadUrl" $zipPath = Join-Path $env:TEMP "chromedriver.zip" Invoke-WebRequest -Uri $downloadUrl -OutFile $zipPath -UseBasicParsing # 解压到目标目录 Expand-Archive -Path $zipPath -DestinationPath $driverDir -Force Remove-Item $zipPath # 添加到系统PATH $path = [Environment]::GetEnvironmentVariable("Path", "User") if ($path -notlike "*$driverDir*") { [Environment]::SetEnvironmentVariable("Path", "$path;$driverDir", "User") } Write-Host "Chromedriver 安装完成! 路径: $driverDir" Write-Host "请关闭所有终端并重新打开以使PATH变更生效" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值