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

Jer*_*ril 5 python beautifulsoup

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

 id = 'priceblock_ourprice',  id = 'priceblock_saleprice', and  id = 'priceblock_dealprice'.
Run Code Online (Sandbox Code Playgroud)

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

m = soup1.find_all('span', {'id': 'priceblock_ourprice'})
Run Code Online (Sandbox Code Playgroud)

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

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

链接1

链接2

链接3

感谢您的帮助!

小智 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)
Run Code Online (Sandbox Code Playgroud)