You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup获取Uber Eats城市返回0而非51个,求解决方法

解决Uber Eats城市抓取返回0的问题

问题原因

  • 动态页面渲染:Uber Eats的城市列表是通过JavaScript动态加载的,直接用urlopen获取的静态HTML中没有实际的城市数据。
  • 动态CSS类名:你代码中使用的av ax ay这类类名是网站动态生成的,会随时变化,无法稳定定位元素。

解决方案:使用Selenium抓取动态内容

Selenium可以模拟浏览器加载页面,获取动态渲染后的完整HTML,再用BeautifulSoup解析。

修改后的代码

# 抓取Uber Eats所有城市
from selenium import webdriver
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
from bs4 import BeautifulSoup
import pandas as pd

# 配置Chrome浏览器选项
chrome_options = Options()
chrome_options.add_argument('--headless=new')  # 无头模式,不显示浏览器窗口
chrome_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 = webdriver.Chrome(options=chrome_options)
URL = "https://www.ubereats.com/location"
driver.get(URL)

# 等待城市列表加载完成(最多等待10秒)
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div[data-testid='location-group']")))

# 获取渲染后的页面源码
webpage = driver.page_source
driver.quit()  # 关闭浏览器

# 解析页面
soup = BeautifulSoup(webpage, 'html.parser')
df = pd.DataFrame(columns=['city', 'state', 'url'])

# 定位所有州/地区分组
state_groups = soup.find_all("div", {"data-testid": "location-group"})

i = 0
for group in state_groups:
    # 获取州/地区名称
    state_name = group.find("h3").text.strip()
    if state_name == "All Countries":
        continue
    print(f"Processing: {state_name}")
    
    # 获取该地区下的所有城市链接
    city_links = group.find_all("a", {"data-testid": "location-link"})
    for link in city_links:
        df.loc[i] = [
            link.text.strip(),
            state_name,
            "https://www.ubereats.com" + link['href']
        ]
        i += 1

print(f"共抓取到{len(df)}个城市")
print(df.head())

代码说明

  • 无头浏览器模式:--headless=new让浏览器在后台运行,不弹出窗口。
  • 等待元素加载:用WebDriverWait确保城市列表元素加载完成后再获取源码,避免因加载延迟导致的空数据。
  • 稳定选择器:使用data-testid属性定位元素,这类属性是为测试设计的,比动态生成的class更稳定。
  • 关闭浏览器:抓取完成后调用driver.quit()释放资源。

内容的提问来源于stack exchange,提问作者Md.Abdul Kader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:54:20