查找HTML响应中是否存在某个标记,并相应地打印if/else

2024-05-14 06:00:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个网站收集数据(使用Python)。在webpage中,有多个软件列表,每个列表中都有。我的数据在标记(h5)和特定类('price_software_details)

但是,在某些情况下,标记和数据一起丢失。我想打印'不适用'的消息,如果数据和标签丢失,否则它应该打印数据

我尝试了下面提到的代码,尽管它不起作用。 救命啊


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


Tags: 数据标记列表软件网站link情况software
2条回答

你需要知道soup.find()永远不会是True,它只会是结果或None

interest = soup.find(id = 'allsoftware')
for link in interest.findAll('h5'):
    if link.find(class_ = 'price_software_details'):
        print(link.getText())
    else:
        print('NA')

您是否尝试过错误处理(try,except)

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

相关问题 更多 >