python - BeautifulSoup 无法找到具有特定类的表

标签 python beautifulsoup

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

"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_all 来查找区域。因此,它会生成结果集,而不仅仅是单个结果(当然该集可以包含一个、零个或多个结果)。我认为有两种选择:

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

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

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

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

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

关于python - BeautifulSoup 无法找到具有特定类的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620432/

相关文章:

python - PostgreSQL NUMERIC 数据类型的 Django 模型字段

python - CPU秒数的理解

python - 使用 MySQLdb 向表中插入行时出错

javascript - Python Selenium,抓取网页 javascript 表

python - 为什么当我使用 beautifulsoup 抓取 HTML 中的字符串时它们不起作用

Python BeautifulSoup - 查找类名称以某个字符串开头的所有元素

python - 在 numpy.where 中访问对象方法?

python - 使用带有 EC2 的 boto 在服务器上处理并取回结果的最有效方法是什么?

python - 如何在 BS4 中搜索包含给定字符串的标签?

带请求的 Python 身份验证。为什么它不起作用? .NET 和维基百科