【问题标题】:Why does find_all give an error even though there is no error in just find? (Python Beautiful Soup)为什么即使 find 没有错误,find_all 也会出错? (蟒蛇美汤)
【发布时间】:2016-03-31 07:17:49
【问题描述】:

我正在尝试从 Billboard 前 100 名中获取歌曲的标题。 图片是他们的html脚本。

我写了这段代码:

from bs4 import BeautifulSoup
import urllib.request

url= 'http://www.billboard.com/charts/year-end/2015/hot-100-songs'
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(), "html.parser")
songtitle = soup.find("div", {"class": "row-title"}).h2.contents
print(songtitle)

它检索第一个标题“UPTOWN FUNK!”
当我使用find_all 时,它给了我错误:

line 6, in <module>
songtitle = soup.find_all("div", {"class": "row-title"}).h2.contents
AttributeError: 'ResultSet' object has no attribute 'h2'

为什么它给我一个错误而不是给我所有的标题?完整的 html 脚本可以在这个网站上使用 chrome 中的 Control Shift J 找到:http://www.billboard.com/charts/year-end/2015/hot-100-songs

【问题讨论】:

    标签: python html python-3.x beautifulsoup html-parsing


    【解决方案1】:

    .find_all() 返回一个ResultSet 对象,它基本上是Tag 实例的列表——它没有find() 方法。您需要遍历find_all() 的结果并在每个标签上调用find()

    for item in soup.find_all("div", {"class": "row-title"}):
        songtitle = item.h2.contents
        print(songtitle)
    

    或者,创建一个CSS selector

    for title in soup.select("div.row-title h2"):
        print(title.get_text())
    

    对了,这个问题是covered in the documentation

    AttributeError: 'ResultSet' object has no attribute 'foo' - 这个 通常发生是因为您希望 find_all() 返回单个标签 或字符串。但是find_all() 返回标签和字符串的list——a ResultSet 对象。您需要遍历列表并查看 .foo 每一个。或者,如果你真的只想要一个结果,你需要 使用find() 而不是find_all()

    【讨论】:

      【解决方案2】:

      find_all 总是返回一个列表。你可以做列表操作。

      例如,

      songtitle = soup.find_all("div", {"class": "row-title"})[0].get
      print songtitle.get('h2')
      songtitle = soup.find_all("div", {"class": "row-title"})[1].get
      print songtitle.get('h2')
      

      输出:

      UPTOWN FUNK!
      THINKING OUT LOUD
      
      for item in soup.find_all("div", {"class": "row-title"}):
          songtitle=item.get('h2')
          print songtitle
      

      【讨论】:

        猜你喜欢
        • 2020-05-03
        • 1970-01-01
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        • 2014-04-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多