BeautifulSoup4如何检查标记是否具有特定的子标记

2024-04-29 10:16:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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语句,使代码仅在主标记没有指定的子标记时打印


Tags: 代码in标记forifbodyh2all
1条回答
网友
1楼 · 发布于 2024-04-29 10:16:21

(Python 3.8.1)
同意@Manali。添加要搜索的标记,就像在soup.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)

这会给你想要的结果

相关问题 更多 >