使用Selenium爬取clutch.io时Chrome二进制文件找不到错误的解决方法
解决Chrome二进制文件找不到的错误及Clutch.io爬取方案
一、修复"cannot find Chrome binary"错误
这个错误的核心是Selenium找不到Chrome浏览器的执行文件,按以下步骤排查解决:
- 确认Chrome已安装:检查系统中是否安装了Google Chrome,未安装则直接下载官方版本安装。
- 指定Chrome安装路径(非默认情况):如果Chrome装在非系统默认位置,初始化Driver时手动指定二进制文件路径:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() # Windows示例路径:"C:\Program Files\Google\Chrome\Application\chrome.exe" # Linux示例路径:"/usr/bin/google-chrome" options.binary_location = "你的Chrome安装路径" driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
- 匹配ChromeDriver与Chrome版本:使用
webdriver_manager库自动下载和当前Chrome版本匹配的ChromeDriver,避免版本不兼容问题(上述代码已集成该逻辑)。
二、Clutch.io可行爬取方案
Clutch.io存在动态加载和反爬机制,以下是优化后的爬取代码:
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import time # 配置Chrome选项 options = webdriver.ChromeOptions() # 无头模式运行,不弹出浏览器窗口 options.add_argument("--headless=new") # 添加模拟浏览器的请求头,规避基础反爬 options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") # 初始化Driver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) url = 'https://clutch.co/it-services/msp' driver.get(url) # 模拟滚动加载全部内容(页面为滚动加载更多) last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) # 等待内容加载完成 new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height # 解析页面数据 soup = BeautifulSoup(driver.page_source, "lxml") links = [] for l in soup.find_all('li', class_='website-link website-link-a'): link = l.a.get('href') if link: links.append(link) print(links, "\n", "Count links - ", len(links)) # 关闭Driver释放资源 driver.quit()
额外反爬建议
- 每次请求或滚动后添加随机延迟(比如1-3秒随机),避免请求频率过高触发反爬。
- 若出现IP封禁,可配置代理IP池切换请求IP。
- 若觉得Selenium过于笨重,可尝试使用
requests-html库替代(支持JS渲染):
from requests_html import HTMLSession import time session = HTMLSession() url = 'https://clutch.co/it-services/msp' r = session.get(url) # 模拟滚动5次加载全部内容,每次等待2秒 r.html.render(scrolldown=5, sleep=2) links = [] for item in r.html.find('li.website-link.website-link-a'): link = item.find('a', first=True).attrs.get('href') if link: links.append(link) print(links, "\n", "Count links - ", len(links)) session.close()
内容的提问来源于stack exchange,提问作者zero
相关产品推荐
相关产品推荐

