首页 > 解决方案 > “str”对象没有属性:BeautifulSoup Python 中的“后代”

问题描述

我正在尝试使用 python 中的 bs4 库获得披萨折扣。但是,无论我尝试什么,我总是得到同样的错误:AttributeError: 'str' object has no attribute 'descendants'. 有人可以帮我理解我做错了什么吗?

这是我的代码:

from bs4 import BeautifulSoup as soup
import requests
url = requests.get('https://www.papajohns.com/order/specials')
data = url.content
items = soup(data, 'html.parser')
discount_list = soup.find_all('p', {'class': 'description'}).text
for each_item in discount_list:
    print(each_item.text)

标签: pythonbeautifulsouppython-requests

解决方案


您的代码中有两个错误:

您正在调用作为库而不是第 6 行中的对象beautifulsoup导入的。您还需要删除@Cz_ 建议的属性。像这样改变这一行:soupitems.text

discount_list = items.find_all('p', {'class': 'description'})

推荐阅读