簡體   English   中英

如何使用BeautifulSoup查找特定標簽

[英]How to find a specific tag using BeautifulSoup

我在這里有HTML源代碼http://pastebin.com/rxK0mnVj 我想檢查Source是否在Image標簽中包含blz-src屬性,並檢查src中是否不包含數據uri,然后返回true或false。

例如,

<img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAQAICRAEAOw==" data-blzsrc="http://1.resources.newtest.strawberrynet.com.edgesuite.net/4/C/lyiTlubX4.webp" width="324" height="60" alt="StrawberryNET" /></a>

由於存在data-blzsrc屬性,但應返回False ,但src屬性包含data:

但是這個 ,

<img src="http://images.akam.net/img1.jpg" data-blzsrc="http://1.resources.newtest.strawberrynet.com.edgesuite.net/4/C/lyiTlubX4.webp" width="324" height="60" alt="StrawberryNET" /></a>

應該返回True因為它包含data-blzsrc屬性,並且src不包含data:

如何在BeautifulSoup中實現這一目標。

如果要查找所有img標簽並對其進行測試,請使用find_all()並檢查屬性,例如:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open('index.html'))

def check_img(img):
    return 'data-blzsrc' in img.attrs and 'data' not in img.get('src', '')

for img in soup.find_all('img'):
    print img, check_img(img)

如果要過濾出符合條件的圖像,可以將attrs參數傳遞給提供字典的find_all() data-blzsrc設置為True以強制其存在,使用一個函數檢查src的值是否不包含data

for img in soup.find_all('img', attrs={'data-blzsrc': True, 'src': lambda x: x and 'data' not in x}):
    print img

嘗試查找所有圖像,並檢查是否存在所需的attr並檢查src屬性的內容。 看一下這個腳本:

from bs4 import BeautifulSoup
html = """
<img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAQAICRAEAOw==" data-blzsrc="http://1.resources.newtest.strawberrynet.com.edgesuite.net/4/C/lyiTlubX4.webp" width="324" height="60" alt="StrawberryNET" /></a>
<img src="http://images.akam.net/img1.jpg" data-blzsrc="http://1.resources.newtest.strawberrynet.com.edgesuite.net/4/C/lyiTlubX4.webp" width="324" height="60" alt="StrawberryNET" /></a>
"""

soup = BeautifulSoup(html)
for img in soup.findAll('img'):
    #here is your desired conditions
    if img.has_attr('data-blzsrc') and not img.attrs.get('src','').startswith('data:'):
        print img

打印所需的img節點

<img alt="StrawberryNET" data-blzsrc="http://1.resources.newtest.strawberrynet.com.edgesuite.net/4/C/lyiTlubX4.webp" height="60" src="http://images.akam.net/img1.jpg" width="324"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM