【问题标题】:BeautifulSoup cannot locate table with specific class [duplicate]BeautifulSoup 无法找到具有特定类的表 [重复]
【发布时间】:2023-04-09 02:41:01
【问题描述】:

基本上,我正在尝试从表中提取具有下面给定类标题的文本。我已经编写了从每一行中提取文本的其余代码,因此在这方面我不需要任何帮助。我似乎无法弄清楚为什么会收到此错误:

"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

代码是:

from bs4 import BeautifulSoup

import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

url  = requests.get("http://www.jsugamecocksports.com/boxscore.aspx?path=baseball&id=4109", headers = header).text

soup = BeautifulSoup(url, 'html.parser')   
region = soup.find_all('div', {'id': 'inning-all'})
table = region.find('table', {'class': 'sidearm-table play-by-play'})

【问题讨论】:

  • 这个错误有什么不清楚的地方?
  • 我应该能够使用 find() 正确地从“区域”中提取相应的表吗?
  • @RickAhif:这并不是 Python 真正遇到的问题,更多的是因为您使用 find_all 搜索了 多个 区域。
  • 错误信息再清楚不过了,也没有迹象表明问题出在其他地方,所以我投票决定关闭它。

标签: python beautifulsoup


【解决方案1】:

问题是您写了一个find_all 来查找该地区。因此,它会生成一组结果,而不仅仅是一个结果(当然该组可以包含一个、零个或多个结果)。我认为有两种选择:

  1. 如果您确定只有一个具有该 id 的 div(通常应该只有一个,您可以使用 find

    region = soup.find('div', {'id': 'inning-all'})
    table = region.find('table', {'class': 'sidearm-table play-by-play'})

    如果有多个:迭代建立的区域,并分别处理它们:

  2. 如果您确定只有一个具有该 id 的 div(通常应该只有一个,您可以使用 find

    regions = soup.find_all('div', {'id': 'inning-all'})
    for region in regions:
        table = region.find('table', {'class': 'sidearm-table play-by-play'})

【讨论】:

  • 感谢您的明确答复。我相信它们应该只适用于给定网站,因此我将继续进行第一次实施。非常感谢!
  • @Willem 你知道在答案 1 或 2 中分配单个变量值的方法
【解决方案2】:

作为替代方案,您可以使用单个CSS selector 来解决问题:

table = soup.select_one('#inning-all table.sidearm-table.play-by-play')

CSS 选择器将匹配table 元素与sidearm-tableplay-by-play 类在具有inning-all id 属性值的元素下。

使用select() 而不是select_one() 来定位与选择器匹配的所有元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2014-05-09
    • 2019-02-21
    相关资源
    最近更新 更多