[英]How to check if BeautifulSoup tag is a certain tag?
如果我使用beautifulsoup
找到某個標簽:
styling = paragraphs.find_all('w:rpr')
我看下一個標簽。 如果它是<w:t>
標簽,我只想使用該標簽。 如何檢查下一個標簽是什么類型的標簽?
我為element.find_next_sibling().startswith('<w:t')
嘗試了element.find_next_sibling().startswith('<w:t')
但它說NoneType object is not callable
。 我也試過element.find_next_sibling().find_all('<w:t'>)
但它沒有返回任何東西。
for element in styling:
next = element.find_next_sibling()
if(#next is a <w:t> tag):
...
我正在使用beautifulsoup
並希望堅持使用它,如果可能的話,不使用eTree
添加eTree
或其他解析器。
使用item.name
您可以看到標簽的名稱。
問題是標簽之間有元素NavigableString
也被視為兄弟元素,它們給出None
。
您將不得不跳過這些元素,或者您可以獲取所有兄弟元素並使用for
循環查找第一個<w:t>
並使用break
退出循環
from bs4 import BeautifulSoup as BS
text = '''<div>
<w:rpr></w:rpr>
<w:t>A</w:t>
</div>'''
soup = BS(text, 'html.parser')
all_wrpr = soup.find_all('w:rpr')
for wrpr in all_wrpr:
next_tag = wrpr.next_sibling
print('name:', next_tag.name) # None
next_tag = wrpr.next_sibling.next_sibling
#next_tag = next_tag.next_sibling
print('name:', next_tag.name) # w:t
print('text:', next_tag.text) # A
#name: None
#name: w:t
#text: A
print('---')
all_siblings = wrpr.next_siblings
for item in all_siblings:
if item.name == 'w:t':
print('name:', item.name) # w:t
print('text:', item.text) # A
break # exit after first <w:t>
#name: w:t
#text: A
編輯:如果你用 HTML 格式測試代碼有點不同
text = '''<div>
<w:rpr></w:rpr><w:t>A</w:t>
</div>'''
那么標簽之間將沒有NavigableString
,第一種方法將失敗,但第二種方法仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.