gpt4 book ai didi

python - 在 BeautifulSoup 中查找标签和文本

转载 作者:可可西里 更新时间:2023-11-01 12:52:59 24 4
gpt4 key购买 nike

我在制定 findAll 时遇到了一些问题查询 BeautifulSoup 会做我想做的事。以前,我使用的是 findAll仅从一些 html 中提取文本,基本上剥离所有标签。例如,如果我有:

<b>Cows</b> are being abducted by aliens according to the
<a href="www.washingtonpost.com>Washington Post</a>.

它将减少为:

Cows are being abducted by aliens according to the Washington Post.

我会使用 ''.join(html.findAll(text=True)) 来做到这一点.这工作得很好,直到我决定只保留 <a>标签,但去掉其余的标签。因此,根据最初的例子,我会这样结束:

Cows are being abducted by aliens according to the
<a href="www.washingtonpost.com>Washington Post</a>.

我最初认为以下方法可以解决问题:

''.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('<b>Cows</b> are being abducted by aliens according to the <a href="www.washingtonpost.com>Washington Post</a>.')
parsed_soup = ''

我们像使用 contents 的列表一样在解析树中导航方法。我们仅在文本是标签且标签不是 <a> 时提取文本.否则我们会得到包含标签的整个字符串。这使用 navigating the parse tree API .

for item in soup.contents:
if type(item) is Tag and u'a' != item.name:
parsed_soup += ''.join(item.findAll(text = True))
else:
parsed_soup += unicode(item)

保留文本的顺序

 >>> print parsed_soup
u'Cows are being abducted by aliens according to the <a href=\'"www.washingtonpost.com\'>Washington Post</a>.'

关于python - 在 BeautifulSoup 中查找标签和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com