【问题标题】:Python - Beautiful Soup OR condition in soup.find_all(....)Python - soup.find_all(....) 中的美丽汤或条件
【发布时间】:2016-04-16 03:52:11
【问题描述】:

我们正在废弃 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'属性值不同的链接:

Link 1

Link 2

Link 3

感谢您的帮助!

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

我尚未对此进行测试,但我相信您可以将函数作为参数传递给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)

【讨论】:

  • 非常感谢。有效。你能解释一下它的工作原理吗? tag 参数在做什么以及如何在没有任何 '()' 的情况下调用 id 'check_id'。我是 python 新手。谢谢
【解决方案2】:

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

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

【讨论】:

【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多