You need to enable JavaScript to run this app. 使用BeautifulSoup爬取页面data-oid属性无输出如何排查解决
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup爬取页面data-oid属性无输出如何排查解决

问题原因

  • 缺少合法请求头:目标站点会校验请求头的User-Agent字段,直接使用requests默认UA发起请求会被拦截,返回的页面内容不包含目标表格元素,调用table.find_all时会直接抛出异常导致程序终止无输出。
  • 属性获取方法写法错误:BeautifulSoup没有get_attrs这个属性获取方法,错误写法会直接触发语法报错,导致程序中断。
  • 未做属性存在校验:不是所有<td>标签都携带data-oid属性,直接强制取值会触发KeyError,同样会导致程序中断。

修复后代码

import requests
from bs4 import BeautifulSoup

url = 'https://www.betexplorer.com/soccer/south-korea/k-league-2/bucheon-fc-1995-jeonnam/EDwej14E/'
# 添加请求头伪装浏览器请求,避免被站点拦截
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', class_='table-main')

# 先校验table是否成功获取,避免空值报错
if table:
    for rows in table.find_all('tr')[1:]:
        for td in rows.find_all('td'):
            # 使用get方法取值,不存在对应属性时返回None,不会触发报错
            data_oid = td.get('data-oid')
            if data_oid:
                print(data_oid)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:12:00