Glovo商品名称与价格爬取问题求助(BeautifulSoup实现遇阻)
解决Glovo站点商品名称与价格爬取问题
核心原因
Glovo的商品数据基本都是动态加载的——页面初始HTML只包含框架结构,商品列表等核心内容是通过后续AJAX请求获取并渲染的。直接用BeautifulSoup解析静态HTML自然找不到嵌套的商品元素。
两种可行解决方案
方案1:直接调用API接口(推荐)
Glovo的商品数据本质是从后端API返回的JSON,抓这个接口比解析HTML高效得多:
- 打开浏览器F12开发者工具,切换到「Network」标签,筛选「XHR/Fetch」类型请求;
- 刷新目标页面,找到返回商品列表的API(通常URL包含
products或merchants关键词); - 复制请求头里的
User-Agent和必要的认证信息(比如Authorization令牌,部分接口需要); - 用
requests请求API并解析JSON,直接提取商品名称和价格。
示例代码:
import requests import sqlite3 # 替换为你找到的实际API地址 API_URL = "https://api.glovoapp.com/v3/merchants/1234/products" HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/118.0.0.0 Safari/537.36", "Authorization": "Bearer your_auth_token_here" # 从浏览器请求头复制 } # 请求API resp = requests.get(API_URL, headers=HEADERS) products = resp.json().get("data", []) # 初始化SQLite数据库 conn = sqlite3.connect("glovo_products.db") cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS products (title TEXT, price REAL, merchant_id TEXT)''') # 写入数据 for item in products: title = item.get("name") # 注意:Glovo价格通常以分为单位,需转换为元/欧元 price = item.get("price", {}).get("amount", 0) / 100 merchant_id = API_URL.split("/")[-2] cursor.execute("INSERT INTO products VALUES (?, ?, ?)", (title, price, merchant_id)) conn.commit() conn.close()
方案2:用Selenium渲染动态页面
如果API接口难以获取(比如需要复杂认证),可以用Selenium模拟浏览器加载页面,等商品渲染完成后再解析:
- 安装Selenium和对应浏览器驱动(比如ChromeDriver);
- 模拟打开目标页面,等待商品列表元素加载完成;
- 用BeautifulSoup解析渲染后的页面源码。
示例代码:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from bs4 import BeautifulSoup import sqlite3 # 初始化Chrome浏览器 driver = webdriver.Chrome() driver.get("https://glovoapp.com/es/barcelona/store/example-store") # 替换为你的测试链接 # 等待商品卡片加载(替换为实际的商品元素选择器) wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "product-card"))) # 解析页面 soup = BeautifulSoup(driver.page_source, "html.parser") product_cards = soup.find_all("div", class_="product-card") # 写入数据库 conn = sqlite3.connect("glovo_products.db") cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS products (title TEXT, price REAL, store_url TEXT)''') for card in product_cards: # 替换为实际的标题和价格元素选择器 title = card.find("h3", class_="product-card__name").text.strip() price_str = card.find("span", class_="product-card__price").text.strip().replace("€", "") price = float(price_str) if price_str else 0.0 cursor.execute("INSERT INTO products VALUES (?, ?, ?)", (title, price, driver.current_url)) conn.commit() conn.close() driver.quit()
注意事项
- 别频繁请求,加个延时(比如
time.sleep(1)),避免被Glovo封IP; - 务必遵守Glovo的网站使用条款,不要用于商业用途;
- API令牌可能会过期,需要定期从浏览器更新。
内容的提问来源于stack exchange,提问作者Davide
相关产品推荐
相关产品推荐

