You need to enable JavaScript to run this app. 使用BS4进行网页抓取出现ResultSet无find_all属性报错如何修复
优惠活动
大模型
产品
解决方案
定价
更多

使用BS4进行网页抓取出现ResultSet无find_all属性报错如何修复

问题修复方案

报错根因

你代码中调用了soup.find_all('tbody').find_all('tr'),find_all()方法返回的是匹配所有tbody标签的ResultSet列表对象,列表本身没有find_all方法,才会触发该属性错误。你注释里标注的find("tbody")才是正确用法,find()返回单个元素,可以继续调用查找方法。

完整修复代码

目前pandas高版本已经移除了DataFrame.append方法,同步替换为更规范的列表暂存+一次性转换写法,还补充了异常判断避免特殊行报错,修复后代码如下:

import pandas as pd
import requests
from bs4 import BeautifulSoup 

url="https://www.cse.lk/pages/trade-summary/trade-summary.component.html"

data  = requests.get(url).text
soup = BeautifulSoup(data, 'html5lib')

# 用列表暂存所有行数据,最后一次性转DataFrame,效率远高于循环拼接
rows_list = []
# 将find_all('tbody')改为find('tbody'),获取单个tbody元素后再查找行
for row in soup.find('tbody').find_all('tr'):
    col = row.find_all("td")
    # 跳过列数不足的空行/异常行,避免索引报错
    if len(col) < 11:
        continue
    Company_Name = col[0].text.strip()
    Symbol = col[1].text.strip()
    Share_Volume = col[2].text.strip()
    Trade_Volume = col[3].text.strip()
    Previous_Close = col[4].text.strip()
    Open = col[5].text.strip()
    High = col[6].text.strip()
    Low = col[7].text.strip()
    Last_Traded_Price = col[8].text.strip()
    Change = col[9].text.strip()
    Change_Percentage = col[10].text.strip()
    rows_list.append({
        "Company Name":Company_Name,
        "Symbol":Symbol,
        "Share Volume":Share_Volume,
        "Trade Volume":Trade_Volume,
        "Previous Close (Rs.)":Previous_Close,
        "Open (Rs.)":Open,
        "High (Rs.)":High,
        "Low (Rs.)":Low,
        "Last Traded Price (Rs.)":Last_Traded_Price,
        "Change (Rs.)":Change,
        "Change Percentage (%)":Change_Percentage
    })

# 批量转换为DataFrame
cse = pd.DataFrame(rows_list)

额外注意事项

如果运行后拿到的DataFrame为空,说明该网站的交易数据是前端JS动态渲染的,静态请求只能拿到页面框架,拿不到实际加载的表格数据,需要换成Selenium、Playwright等动态渲染工具爬取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 12:27:03