python - 'NoneType' 对象在使用 beautifulsoup 进行网络爬行时没有属性'text'
问题描述
我在尝试抓取网络数据时出错,错误消息说
标签信息:“NoneType”对象没有属性“文本”
try:
label_info = soup.find('div', {'class': 'h-bg-white h-margin-a-default'})
if debug: print('Label info:',label_info.text)
if debug: print('')
except Exception as e:
label_info = ''
if debug: print("Label info:", e)
pass
谁能指导我为什么这不起作用?
解决方案
您可以将 CSS 类指定为字符串列表,而不是一个字符串:
import requests
from bs4 import BeautifulSoup
url = 'https://www.target.com/p/nong-shim-noodle-bowl-soup-spicy-kimchi-flavor-3-03oz/-/A-15137591#lnk=sametab'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
print(soup.find('div', {'class': ['h-bg-white', 'h-margin-a-default']}).get_text(strip=True, separator='\n'))
印刷:
Highlights
Spicy kimchi flavor
Fresh noodle texture and robust flavor
Ready in only 3 minutes— just add hot water
Convenient on-the-go meal
推荐阅读
- elm - 如何使用 elm-bootstrap 4.1.0 制作条纹表?
- javascript - CKEDITOR - 插入 html 文本或 img 单击 CKEDITOR 外部的某些 DIV
- javascript - Firebase With Web:在参考中使用用户 ID 会导致错误:未捕获的 TypeError:无法读取未定义的属性“on”
- android - 对于特定布局/资源的 LTR,即使在 RTL 中运行
- javascript - 如何在另一个组件中访问一个组件的常量变量 - React
- python - Python2:以列表格式打印函数的布尔结果
- reactjs - 使用 create-react-app 设置 Mobx 时的问题
- java - 使用 Angular 7 前端启动 Spring-Boot 应用程序时无法加载资源错误(缺少资源)
- firebase - 我可以将 OneSignal 令牌导入 FCM 吗?
- android - 从另一个活动更新首选项 UI 实例?