父-子标签上的BeautifulSoup findall

2024-06-25 23:56:29 发布

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

我用的是bs4。在

在一堆HTML中有:

<li><strong>some text</strong></li>

我想做一个find_all找到它。当然find_all('li')可以工作,但是必须有一种方法来指定查找父子组合。在


Tags: 方法texthtmlsomeliallfindstrong
2条回答

这是另一种选择。在

>>> from bs4 import BeautifulSoup
>>> data = "<li><strong>some text</strong></li>"
>>> soup = BeautifulSoup(data)
>>> soup.find('li')
<li><strong>some text</strong></li>
>>> soup.find('li').find('strong')
<strong>some text</strong>
>>> soup.find('li').find('strong').text
u'some text'
>>> 

我想^{}就是你要问的问题:

soup.select('li > strong')

这将找到所有strong标记,它们是li标记的直接子级。在

演示:

^{pr2}$

相关问题 更多 >