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

为何BeautifulSoup无法定位HTML中的特定赛马表单表格元素?

无法获取赛马表单表格文本的解决方法

问题描述

我无法通过代码获取高亮显示的赛马表单(race form)表格中的文本,请问应使用哪些合适的元素来获取该文本?以下是我编写的Python爬虫代码:

import requests
from bs4 import BeautifulSoup

# 目标网页URL
url = "https://www.racingandsports.com.au/thoroughbred/horse/smokin-rubi/1978955"

# 请求头配置
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'
}

# 发送GET请求
response = requests.get(url, headers=headers)

# 解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')

# 查找指定类名的表格元素
table_element = soup.find('table', class_='table table-condensed table-striped table-hover tbl-race-form')

# 提取并打印表格文本
if table_element:
    table_text = table_element.get_text(separator='\n', strip=True)
    print(table_text)
else:
    print("未找到指定类名的表格。")

解决思路与方案

1. 处理动态加载内容

这类赛马网站的表单表格通常是通过JavaScript动态渲染的,requests只能抓取页面初始的静态HTML,无法获取JS加载后的动态内容。此时可以用Selenium或Playwright模拟浏览器行为,等待页面完全加载后再抓取:

示例代码(Selenium):

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# 配置无头浏览器模式
options = Options()
options.add_argument('--headless=new')
options.add_argument('--disable-gpu')

# 初始化浏览器驱动
driver = webdriver.Chrome(options=options)
driver.get("https://www.racingandsports.com.au/thoroughbred/horse/smokin-rubi/1978955")

# 隐式等待5秒,确保表格加载完成
driver.implicitly_wait(5)

# 通过核心类名定位表格
table_element = driver.find_element(By.CLASS_NAME, "tbl-race-form")
# 提取表格文本
table_text = table_element.text
print(table_text)

# 关闭浏览器
driver.quit()

2. 验证元素选择器正确性

用浏览器开发者工具(F12)检查页面结构:

  • 确认表格的class是否准确:搜索tbl-race-form,查看是否存在该类名的表格元素
  • 检查表格是否嵌套在iframe中:如果是,需要先切换到iframe再定位元素,示例代码:
# 找到iframe并切换上下文
iframe = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(iframe)
# 之后再执行表格定位逻辑

3. 应对反爬机制

部分网站会通过Cookies、会话验证阻止爬虫:

  • 使用requests.Session()维持会话,先访问首页获取Cookies再请求目标页面
  • 补充完整请求头,添加Referer、Accept-Language等字段,增强请求的真实性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:08:14