首页 > 解决方案 > 查找 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')

标签: pythonhtmlweb-scrapingbeautifulsouppython-requests

解决方案


您是否尝试过错误处理(尝试,除外)?

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')

推荐阅读