【发布时间】:2011-08-07 21:00:30
【问题描述】:
我在为 BeautifulSoup 制定 findAll 查询时遇到了一些麻烦,该查询可以满足我的需求。以前,我使用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> 标签。重要的是标签要围绕在它们标记的文本周围——我不能让标签或文本出现乱序。
有什么想法吗?
【问题讨论】:
标签: python html beautifulsoup