我在为BeautifulSoup编写findAll查询时遇到了麻烦,它将执行我想要的操作.以前,我使用findAll从某些html中仅提取文本,实质上是剥离所有标签.例如,如果我有:
Cows are being abducted by aliens according to the
我最初认为以下方法可以解决问题:
''.join(html.findAll({'a':True}, text=True))
但是,这是行不通的,因为text = True似乎表明它将只能找到文本.我需要的是一些OR选项-我想找到文本OR< a>标签.重要的是,标签必须留在要标记的文本周围-我不能使标签或文本乱序显示.
有什么想法吗?
解决方法:
注意:BeautifulSoup.findAll是搜索API. findAll的第一个命名参数即name可以用于将搜索限制为给定的一组标签.仅使用单个findAll就不可能选择标签之间的所有文本,而同时选择< a>的文本和标签.因此,我提出了以下解决方案.
此解决方案取决于导入的BeautifulSoup.Tag.
from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup('Cows are being abducted by aliens according to the Washington Post.'
标签:beautifulsoup,html,python
来源: https://codeday.me/bug/20191102/1990639.html