[英]How to find specific script tag from a webpage using 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.