ChromeDriver无头模式interest-cohort权限错误及Manta爬取失败求助
问题分析与解决方案
一、问题拆解
1. "interest-cohort" 错误提示
这个是浏览器控制台的警告,完全不影响爬虫运行,属于网站自身的HTTP头配置问题,和你的代码无关,直接忽略即可。
2. 输出空列表的核心原因
- XPath定位错误:你用的是绝对路径
/html/body/main/div[3]/div[1]/div[1]/div[2],仅指向一个包含餐厅卡片的父容器,而非单个餐厅节点;且绝对路径容错率极低,页面布局稍有变化就会失效。 - 无头模式被识别:默认的headless模式容易被网站判定为爬虫,导致内容无法正常加载。
二、修正后的代码示例
import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # ChromeDriver路径 webdriver_service = Service('C:\webdrivers') # 配置Chrome,模拟正常浏览器行为 chrome_options = Options() chrome_options.add_argument('--headless=new') # 新版无头模式,更接近真实浏览器 chrome_options.add_argument('--disable-blink-features=AutomationControlled') # 禁用自动化识别 chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36') chrome_options.add_argument('--window-size=1280x720') driver = webdriver.Chrome(service=webdriver_service, options=chrome_options) url = "https://www.manta.com/search?search=Restaurants&context=unknown&search_source=nav&city=Dallas&state=Texas&country=United%20States&pt=32.7936%2C-96.7662&device=desktop&screenResolution=1280x720" driver.get(url) # 用显式等待替代固定sleep,更高效可靠 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'search-result')]")) ) # 用相对路径定位所有餐厅卡片,稳定性更高 listings = driver.find_elements(By.XPATH, "//div[contains(@class, 'search-result-card')]") # 提取名称与电话 for idx, listing in enumerate(listings, 1): try: name = listing.find_element(By.XPATH, ".//h3").text phone = listing.find_element(By.XPATH, ".//a[contains(@href, 'tel:')]").text print(f"餐厅{idx}: {name} | 电话: {phone}") except Exception as e: print(f"提取餐厅{idx}信息失败: {str(e)}") driver.quit()
三、动态网页爬取学习资源
书籍
- 《Python网络爬虫从入门到实践》:覆盖静态、动态页面爬取,包含Selenium、Scrapy的实战案例,适合从入门到进阶。
- 《Web Scraping with Python》:经典英文原版书籍,讲解各类爬取技巧与动态页面处理方案,内容全面且权威。
网站
- 官方文档:Selenium官方文档、ChromeDriver官方文档,提供最准确的参数配置与用法说明。
- 国内技术社区:掘金、CSDN的爬虫专栏,有大量实战教程与踩坑经验分享。
- 交互式教程:Codecademy的Python爬虫课程,边学边练,适合零基础快速上手。
内容的提问来源于stack exchange,提问作者kalyan
相关产品推荐
相关产品推荐

