[英]BeautifulSoup: extracting HTML tag attributes
僅當text=True
而不指定標簽時,才可以獲取HTML標簽屬性。
例:
html=<p class="c4">SOMETEXT</p>
我可以做:
[tag.attrs for tag in soup.findAll('p')]
>>> [[(u'class', u'c1')]]
有沒有辦法做:
[text.attrs for text in soup.findAll(text=True)]
幫忙多謝!
問題已經明確,您認為您需要這樣做:
[tag.attrs for tag in soup.findAll(True) if tag.string]
.findAll(True)
返回文檔中的所有標記,因此即使它們為空,它們也將具有.attr
,如果標記具有.string
內容,則將對其進行過濾。
>>> from bs4 import BeautifulSoup as bs
>>> html = '<p class="c4">SOMETEXT</p><p class="c5"></p>'
>>> soup = bs(html)
>>> [tag.attrs for tag in soup.findAll('p') if tag.string]
[{'class': ['c4']}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.