![](/img/trans.png)
[英]Extracting text node inside a tag that has a child element in beautifulsoup4
[英]BeautifulSoup4 how to check if a tag has a specific child tag
我有以下代碼:
b = soup.find('body')
for t in b.find_all(recursive=False):
if not t.find(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
print(t.get_text())
它應該打印t
所有不是'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
(即標題)的子標簽。
相反,它什么也不打印。 如何修復此 if 語句,以便僅在主標記沒有指定的子標記時才打印代碼?
(Python 3.8.1)
同意@Manali。 添加您要搜索的標簽,就像您在sound.find('body') 中所做的那樣。
soup.html.find_all("<tag name>", recursive=False)
(編輯):
不能直接使用 TAG,請改用 TAG.NAME。
使用: if t.name not in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
而不是: if not t.find(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
否則請嘗試以下代碼段:
b = soup.find('body')
children = b.findChildren(recursive=False)
for child in children:
if child.name not in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
print(child.name)
這應該會給你想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.