使用Selenium+Streamlit编写网页爬虫时浏览器启动后立即崩溃,报InvalidArgumentException错误
Selenium+Streamlit编写网页爬虫时浏览器启动后立即崩溃,报InvalidArgumentException错误
看起来你遇到的是Selenium与Chrome版本不匹配,加上启动配置不完善导致的崩溃问题,结合Streamlit的运行环境,我给你梳理下解决步骤:
1. 优先确认ChromeDriver与Chrome版本严格匹配
你的Chrome版本是131.0.6778.205,必须下载完全对应版本的ChromeDriver:
- 版本号的前三位(131.0.6778)必须和Chrome完全一致,版本不匹配是触发
InvalidArgumentException的最常见原因。 - 下载后将ChromeDriver放在项目根目录,或者配置到系统环境变量中,让Python能直接找到它。
2. 修正Selenium爬虫代码(核心修复)
你当前的代码创建了ChromeOptions但未实际使用,且没有按Selenium 4.x+的规范初始化Driver实例。结合Streamlit的运行环境,需要添加无头模式等适配参数,修改后的scrape.py代码如下:
import selenium.webdriver as webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def scrape_website(website): print("Launching the browser!") # 配置Chrome启动参数,适配Streamlit的运行环境 chrome_options = Options() # 无头模式:避免需要桌面环境才能启动Chrome chrome_options.add_argument("--headless=new") # 禁用GPU渲染,减少环境依赖 chrome_options.add_argument("--disable-gpu") # 禁用沙箱模式,解决部分环境下的权限问题 chrome_options.add_argument("--no-sandbox") # 禁用共享内存,避免内存资源冲突 chrome_options.add_argument("--disable-dev-shm-usage") # 隐藏自动化提示,避免网站检测 chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False) # 初始化Service,指定ChromeDriver路径(如果没配置环境变量,就写绝对路径,比如 "./chromedriver.exe" 或 "/usr/local/bin/chromedriver") service = Service(executable_path="./chromedriver") try: # 将配置好的Options和Service传给Chrome构造函数 driver = webdriver.Chrome(service=service, options=chrome_options) driver.get(website) # 用显式等待替代time.sleep,更可靠地判断页面加载状态 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, "body")) ) print("The page is loaded now...") html = driver.page_source return html finally: # 确保Driver实例被正确关闭,避免资源泄漏 if 'driver' in locals(): driver.quit()
3. Streamlit环境的额外配置
- 本地运行:如果是在Windows/macOS/Linux本地运行,Linux/macOS用户需要给ChromeDriver添加可执行权限,执行命令:
chmod +x chromedriver。 - 部署到Streamlit Cloud:需要在项目根目录创建两个文件:
requirements.txt:添加项目依赖selenium>=4.10.0 streamlitpackages.txt:安装Chrome及Driver的系统依赖chromium-chromedriver chromium-browser
错误原因解析
你遇到的InvalidArgumentException主要由两个问题导致:
- Chrome与ChromeDriver版本不匹配,导致Driver无法与Chrome建立有效通信。
- 未配置适配Streamlit环境的Chrome启动参数,浏览器因环境限制(如无桌面环境、权限不足)启动失败,进而抛出参数错误。
备注:内容来源于stack exchange,提问作者Nikolai Romanov Belliovichksky
相关产品推荐
相关产品推荐

