python - 我想用 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'
能否请你帮忙?
解决方案
错误信息说明了一切
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
推荐阅读
- php - 方形付款表格php检查客户是否存在于目录中并付款
- javascript - &&=、||= 和 ??= 的作用是什么?
- mysql - 保存到sql时如何设置特定列?
- javascript - 在没有 ref 的情况下获取渲染的元素尺寸和属性(元素是一个反应功能组件)
- c# - 是什么阻止了我的列表数据在我的 DataGridView 中显示?
- node.js - 如何使用 Spectron 执行 getPath?
- laravel - laravel eloquent 错误,我无法使用 groupBy 方法创建 created_at
- html - 移动到 VPS 后,来自 http 站点的 Html 图像未显示在 Chrome 中的我的 https 站点上
- amazon-web-services - 如何在 AWS CDK 中获取当前组织的 ID?
- c# - 如果未通过身份验证,如何显示登录页面?