BeautifulGroup循环问题ResultSet对象没有属性“%s”

2024-04-16 22:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码起作用:

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 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 'prettify'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

我不明白为什么它在一个范围内有效,但对二个范围无效。我认为这可能是一个时间问题,所以我在它继续下一个迭代之前增加了5秒的延迟,但这没用。在


Tags: youurlgetobjectrangefindprettifycall
1条回答
网友
1楼 · 发布于 2024-04-16 22:48:54

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

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

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

^{pr2}$

相关问题 更多 >