繁体   English   中英

Python - soup.find_all(....) 中的美丽汤或条件

[英]Python - Beautiful Soup OR condition in soup.find_all(....)

我们正在废弃 Amazon.in 网站以检索任何产品的价格。 所有产品在“span”标签中的“id”属性都有不同的值,例如;

 id = 'priceblock_ourprice',  id = 'priceblock_saleprice', and  id = 'priceblock_dealprice'.

我们的任务是使用 Beautiful Soup 中的 find_all(..) 方法检索产品的价格。 根据我们的基本知识,我们只能为 find_all(..) 方法提供一个参数,如下所示:

m = soup1.find_all('span', {'id': 'priceblock_ourprice'})

有没有办法使用 OR 条件为 find_all(..) 方法提供多个参数?

以下是具有相同“id”属性的不同值的链接:

链接 1

链接 2

链接 3

谢谢您的帮助!

我还没有测试过这个,但我相信你可以将一个函数作为参数传递给find_all()这样你就可以尝试这样的事情:

def check_id(tag):
    valid_ids = ['priceblock_ourprice','priceblock_saleprice','priceblock_dealprice']
    if tag.has_attr('id'):
        return tag['id'] in valid_ids
    else:
        return False

m = soup1.find_all(check_id)

您可以在 find_all 参数中添加您的条件,如下所示:

td_tag_list = soup.find_all(
            lambda tag:tag.name == "span" and
            'id' in tag.attrs and tag.attrs['id'] == 'priceblock_ourprice')

对于那些想知道是否可以避免脚本过于复杂的人。 只需在 find 语句中传递一个列表就可以很好地工作,如下所示:

find_all(name='div', attrs={'class': 
[...
'one_sixth grey_block new-secondary-background result-item',
'one_sixth grey_block new-secondary-back', 
...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM