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

使用Beautiful Soup抓取指定span类返回空列表,求解决方案

解决Beautiful Soup无法抓取动态加载元素的问题

为什么你的代码抓不到目标元素

  • 你用requests.get()获取的是服务器返回的静态HTML源码,但该页面的比赛数据是通过JavaScript动态渲染加载的,静态源码里根本不存在player-matches__tournament-location类的元素,所以BeautifulSoup自然找不到。
  • 网站可能存在基础反爬机制(比如校验请求头的User-Agent),但这不是本次抓取失败的主要原因。

两种可行的修改方案

方案一:用Selenium模拟浏览器渲染(直观易实现)

Selenium会模拟真实浏览器打开页面,等待JS加载完成后再获取渲染后的页面源码,这样就能拿到包含目标元素的内容:

from selenium import webdriver
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

url = "https://www.wtatennis.com/players/326408/iga-swiatek/#matches"

# 初始化Chrome浏览器(需提前下载对应版本的chromedriver)
driver = webdriver.Chrome()
driver.get(url)

# 等待目标元素加载完成,最长等待10秒
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "player-matches__tournament-location"))
    )
finally:
    # 获取渲染后的完整页面源码
    page_source = driver.page_source
    driver.quit()

# 解析页面
soup = BeautifulSoup(page_source, 'html.parser')
spans = soup.find_all('span', class_="player-matches__tournament-location")

# 输出结果
for span in spans:
    print(span.text.strip())

注意:需要下载与你的Chrome浏览器版本匹配的chromedriver,并将其路径配置到环境变量或代码中。

方案二:直接调用数据接口(更高效)

打开浏览器的开发者工具(F12),切换到「Network」标签页,刷新页面后筛选「XHR」请求,能找到加载比赛数据的API接口。直接请求该接口获取JSON数据,比解析HTML更高效:

import requests

# 配置请求头,模拟浏览器请求
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
# 示例API地址(实际地址需从开发者工具中捕获)
api_url = "https://api.wtatennis.com/player/326408/matches?page=1&type=singles&timeFrame=all"

response = requests.get(api_url, headers=headers)
data = response.json()

# 从JSON数据中提取地点信息(字段名需根据实际API返回调整)
for match in data.get('matches', []):
    print(match['tournament']['location'])

注意:API地址和返回字段可能会随网站更新变化,需自行验证。

额外注意事项

  • 不要短时间内频繁发送请求,避免触发网站反爬机制导致IP被封禁。
  • 若使用API方案,需注意请求头中的必要参数(如Referer、Authorization等),这些参数可从开发者工具的请求详情中查看。

内容的提问来源于stack exchange,提问作者Martinis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:45:33