python - 查找 HTML 响应中是否存在某些标签并相应地打印 if/else
问题描述
我正在尝试从网站收集数据(使用 Python)。在 awebpage
中,有多个软件列表,并且在每个列表中。我的数据在一个标签(h5)
和某个类('price_software_details)
中。
但是,在某些情况下,标签和数据会丢失。如果数据和标签丢失,我想打印“NA”消息,否则它应该打印数据。
我尝试了下面提到的代码,尽管它不起作用。请帮忙!
interest = soup.find(id = 'allsoftware')
for link in interest.findAll('h5'):
if link.find(class_ = 'price_software_details') == True:
print(link.getText())
else:
print('NA')
解决方案
您是否尝试过错误处理(尝试,除外)?
interest = soup.find(id='allsoftware')
for link in interest.findAll('h5'):
try:
item = link.find({'class':'price_software_details'})
print(item.get_text())
except:
print('NA')
推荐阅读
- haskell - Haskell 类型检查和确定性
- javascript - 我如何在客户端写一个承诺
- javascript - 当浏览器失去互联网连接时,Websocket 连接关闭
- javascript - 选定的下拉值未显示在 React 的按钮中
- php - 我想使用 PHP 将我的产品加载为网格
- javascript - 在 IE 中运行 Angular 5 应用程序而不使用“import 'core-js/es6/reflect' 和 import 'core-js/es7/reflect'”
- f# - 使用不同的值更改列表的特定元素
- c# - 通过 c# 进程在 vlc 中打开媒体时拆分路径
- python - 从列表中替换子字符串的有效方法
- css - css中的单个固定位置剪切区域仅影响图像