【问题标题】:BeautifulSoup loop issues - ResultSet object has no attribute '%sBeautifulSoup 循环问题 - ResultSet 对象没有属性 '%s
【发布时间】:2018-03-27 22:55:46
【问题描述】:

以下代码有效:

for i in range(0,1):
    url = "https://www.blah.com/" + get_chapter(chron_list[i])
    book = requests.get(url, headers=headers)
    c = book.content
    soup = soup(c, "html.parser")
    print(soup.prettify())

如果我更改为range(1,2),它也可以工作,因为我在chron_list 中有两个项目。但是当我将其更改为 range(0,2) 时,它不再起作用并给我以下错误:

"ResultSet 对象没有属性 '%s'。您可能正在处理一个 像单个项目一样的项目列表。当你调用 find_all() 意思是调用 find()?” % key AttributeError: ResultSet object has no 属性“美化”。您可能正在将项目列表视为 单项。当你打算调用 find() 时,你调用了 find_all() 吗?

我不明白为什么它适用于 1 的范围,但不适用于 2 的范围。我想这可能是时间问题,所以我在它继续下一次迭代之前添加了 5 秒的延迟,但这没有用。

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

您在代码中重新定义 soup。在循环的两次迭代之后,soup 将不再引用 BeautifulSoup,而是引用 soup(c, "html.parser") 返回的对象:

soup = soup(c, "html.parser")
^^^^^^^^^^^

不要重命名BeautifulSoup(或者如果要重命名,请选择其他名称):

from bs4 import BeautifulSoup

...

soup = BeautifulSoup(c, "html.parser")

【讨论】:

  • 宾果游戏!谢谢。
猜你喜欢
  • 2016-12-19
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2018-08-06
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多