用Cursor与Chrome插件爬取网页数据
当我们使用Cursor(一个基于AI的代码编辑器)结合Chrome插件来爬取网页数据。正常情况下,我们可以使用Python的库如requests
和BeautifulSoup
,因为有时网页是动态加载的(通过JavaScript),这就需要我们我们用Selenium来模拟浏览器操作。
然而,之前有提过使用Chrome插件。这里可能指的是使用浏览器插件(如爬虫插件)或者使用Chrome的开发者工具来辅助爬取。但结合Cursor(一个代码编辑器),我们更可能是在编写代码。
要使用 Cursor 编辑器配合 Chrome 插件爬取网页数据,通常有两种主流方案:直接使用 Python 爬虫库或结合浏览器自动化工具。以下是我例举的两个详细步骤和代码示例:
方案一:Python 爬虫库(Requests + BeautifulSoup)
适合静态网页(无需 JS 渲染)
import requests
from bs4 import BeautifulSoupurl = "https://example.com"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}# 发送请求
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')# 示例:提取所有标题
titles = soup.select('h1.title') # 根据实际CSS选择器修改
for title in titles:print(title.text.strip())
方案二:浏览器自动化(Selenium)
适合动态网页(需要 JS 渲染)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By# 配置 Chrome 选项
chrome_options = Options()
chrome_options.add_argument("--headless") # 无头模式
chrome_options.add_argument("--disable-gpu")# 启动浏览器(需下载 chromedriver)
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://example.com")# 等待元素加载(示例)
driver.implicitly_wait(10)# 提取数据
items = driver.find_elements(By.CSS_SELECTOR, ".product-item")
for item in items:name = item.find_element(By.CSS_SELECTOR, ".name").textprice = item.find_element(By.CSS_SELECTOR, ".price").textprint(f"{name}: {price}")driver.quit()
配合 Chrome 插件辅助爬取
-
SelectorGadget(提取 CSS 选择器)
- 安装链接:Chrome Web Store
- 用法:点击页面元素生成 CSS 选择器
-
XPath Helper(提取 XPath)
- 安装链接:Chrome Web Store
-
JSON Viewer(解析 API 数据)
- 用于抓取通过 AJAX 加载的数据(查看 Network 中的 XHR 请求)
进阶技巧:直接调用 Chrome DevTools
使用 undetected-chromedriver
避免反爬:
import undetected_chromedriver as ucdriver = uc.Chrome(headless=True)
driver.get("https://example.com")
# ...操作同 Selenium...
注意事项
- 遵守
robots.txt
和网站使用条款 - 添加延时避免频繁请求(
import time; time.sleep(2)
) - 使用代理 IP 应对反爬机制
- 动态网站优先检查是否有隐藏 API(通过 Network 面板)
提示:在 Cursor 中运行 Selenium 需要先安装依赖:
pip install selenium beautifulsoup4 requests undetected-chromedriver
最后我要提醒大家,我们在选择方案时候需要考虑目标网站的复杂度选择,静态页面用方案一更高效,动态内容用方案二更可靠。