首页 > 解决方案 > 我想用 BeautifulSoup 在 python 中抓取,但 'str' 对象没有属性 'find_all' 发生错误

问题描述

我想用 BeautifulSoup 在 python 中抓取,但 'str' 对象没有属性 'find_all' 发生错误。预期的结果是为数组中的每个值分配数字。

这是我的代码

import requests
from bs4 import BeautifulSoup

url = "https://ja.wikipedia.org/wiki/メインページ"

response= requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
today = soup.find("div", attrs={"id": "on_this_day"}).text

entries = today.find_all("li")
today_list = []
index = 1

for entry in entries:
    today_list.append([index, entry.get_text()])
    index += 1
print(today_list)

错误信息

AttributeError                            Traceback (most recent call last)
<ipython-input-10-c70240e5052b> in <module>
     8 today = soup.find("div", attrs={"id": "on_this_day"}).text
     9 
     ---> 10 entries = today.find_all("li")
    11 today_list = []
    12 index = 1

AttributeError: 'str' object has no attribute 'find_all'

能否请你帮忙?

标签: python

解决方案


错误信息说明了一切

AttributeError: 'str' object has no attribute 'find_all'

因此,您正在尝试获取某些 str 对象的 find_all() 属性。很明显,有一个字符串对象不应该是字符串。

你注意到这里

today = soup.find("div", attrs={"id": "on_this_day"}).text

你有一个.text在这里使它成为一个字符串,所以如果你不希望它成为一个字符串,你只需删除它,这就是你的解决方案!

today = soup.find("div", attrs={"id": "on_this_day"}).text

推荐阅读