簡體   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