- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Beautiful Soup从网页中提取“内容”。我知道有人问过这个 question之前,他们都指向 Beautiful Soup,这就是我开始使用它的方式。
我能够成功获取大部分内容,但我遇到了一些挑战,这些标签是内容的一部分。 (我从一个基本策略开始:如果一个节点中有超过 x 个字符,那么它就是内容)。下面以html代码为例:
<div id="abc">
some long text goes <a href="/"> here </a> and hopefully it
will get picked up by the parser as content
</div>
results = soup.findAll(text=lambda(x): len(x) > 20)
当我使用上面的代码获取长文本时,它在标签处中断(识别的文本将从'and hopefully..'开始)。所以我尝试用纯文本替换标签,如下所示:
anchors = soup.findAll('a')
for a in anchors:
a.replaceWith('plain text')
上面的代码不起作用,因为 Beautiful Soup 将字符串作为 NavigableString 插入,当我将 findAll 与 len(x) > 20 一起使用时会导致同样的问题。我可以先使用正则表达式将 html 解析为纯文本,清除所有不需要的标签,然后调用 Beautiful Soup。但我想避免两次处理相同的内容——我正在尝试解析这些页面,以便我可以显示给定链接的内容片段(非常像 Facebook 分享)——如果一切都用 Beautiful Soup 完成,我想它会更快。
所以我的问题是:有没有一种方法可以使用 Beautiful Soup 来“清除标签”并将它们替换为“纯文本”。如果没有,最好的方法是什么?
感谢您的建议!
更新 Alex 的代码在示例中运行良好。我还尝试了各种边缘情况,它们都运行良好(经过以下修改)。所以我在现实生活中的网站上试了一下,但遇到了让我困惑的问题。
import urllib
from BeautifulSoup import BeautifulSoup
page = urllib.urlopen('http://www.engadget.com/2010/01/12/kingston-ssdnow-v-dips-to-30gb-size-lower-price/')
anchors = soup.findAll('a')
i = 0
for a in anchors:
print str(i) + ":" + str(a)
for a in anchors:
if (a.string is None): a.string = ''
if (a.previousSibling is None and a.nextSibling is None):
a.previousSibling = a.string
elif (a.previousSibling is None and a.nextSibling is not None):
a.nextSibling.replaceWith(a.string + a.nextSibling)
elif (a.previousSibling is not None and a.nextSibling is None):
a.previousSibling.replaceWith(a.previousSibling + a.string)
else:
a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling)
a.nextSibling.extract()
i = i+1
当我运行上面的代码时,出现以下错误:
0:<a href="http://www.switched.com/category/ces-2010">Stay up to date with
Switched's CES 2010 coverage</a>
Traceback (most recent call last):
File "parselink.py", line 44, in <module>
a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling)
TypeError: unsupported operand type(s) for +: 'Tag' and 'NavigableString'
当我查看 HTML 代码时,'Stay up to date..' 没有任何 previous sibling 姐妹(我不知道 previous sibling 姐妹是如何工作的,直到我看到 Alex 的代码并且根据我的测试它看起来像是在寻找标记前的“文本”)。所以,如果没有 previous sibling 姐妹,我很惊讶它没有通过 a.previousSibling is None 和 a;nextSibling is None 的 if 逻辑。
你能告诉我我做错了什么吗?
-ecognium
最佳答案
适用于您的特定示例的方法是:
from BeautifulSoup import BeautifulSoup
ht = '''
<div id="abc">
some long text goes <a href="/"> here </a> and hopefully it
will get picked up by the parser as content
</div>
'''
soup = BeautifulSoup(ht)
anchors = soup.findAll('a')
for a in anchors:
a.previousSibling.replaceWith(a.previousSibling + a.string)
results = soup.findAll(text=lambda(x): len(x) > 20)
print results
发射
$ python bs.py
[u'\n some long text goes here ', u' and hopefully it \n will get picked up by the parser as content\n']
当然,您可能需要多加注意,即,如果没有 a.string
怎么办? ,或者如果 a.previousSibling
是None
-- 你需要合适的 if
声明来处理这种极端情况。但我希望这个总体思路可以帮助你。 (事实上 ,如果 next 兄弟是一个字符串,您可能希望也合并它 - 不确定它如何与您的启发式算法一起使用 len(x) > 20
,但例如说您有两个 9 个字符的字符串,<a>
中间包含一个 5 个字符的字符串,也许你想把这批货当作“23 个字符的字符串”?我不知道,因为我不知道了解启发式的动机)。
我想除了<a>
您还需要删除其他标签,例如 <b>
或 <strong>
, 也许 <p>
和/或 <br>
, ETC...?我想这也取决于您的启发式背后的实际想法是什么!
关于python - 使用 Beautiful Soup Python 模块将标签替换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061718/
我注意到一个非常烦人的错误:BeautifulSoup4(包:bs4)经常发现比以前版本(包:BeautifulSoup)更少的标签。 这是该问题的一个可重现的实例: import requests
我正在尝试从具有我所知道的特定ID的表中获取数据。 由于某种原因,该代码不断给我“无”结果。 我正在尝试从HTML代码中解析: שווי שוק (אלפי ש"ח)
我正在尝试从包含以下 HTML 的网站中提取价格: $ 29.99 我正在使用以下 Beautiful Soup 代码: book_prices = soup_pack
我做了一个网络爬虫,它从一个文本文件中获取数千个 Urls,然后爬取该网页上的数据。 现在它有很多网址;一些网址也被破坏了。 所以它给了我错误: Traceback (most recent call
我正在尝试加载 html 页面并输出文本,即使我正确获取网页,BeautifulSoup 以某种方式破坏了编码。 来源: # -*- coding: utf-8 -*- import requests
目录 beautiful soup库的安装 beautiful soup库的理解 beautiful soup库的引用 BeautifulSoup类
Beautiful Soup就是Python的一个HTML或XML的解析库,可以用它来方便地从网页中提取数据。它有如下三个特点: Beautiful Soup提供一些简单的、Python式的
题目地址:https://leetcode.com/problems/beautiful-arrangement/description/ 题目描述 Suppose you have N inte
题目地址:https://leetcode.com/problems/beautiful-array/description/ 题目描述 Forsome fixed N, an array A i
您好,我正在尝试从网站获取一些信息。请原谅我,如果我的格式有任何错误,这是我第一次发布到 SO。 soup.find('div', {"class":"stars"}) 从这里我收到 我需要 “
我想从 Google Arts & Culture 检索信息使用 BeautifulSoup。我检查了许多 stackoverflow 帖子( [1] , [2] , [3] , [4] , [5]
我决定学习 Python,因为我现在有更多时间(由于大流行)并且一直在自学 Python。 我试图从一个网站上刮取税率,几乎可以获得我需要的一切。下面是来自我的 Soup 变量以及相关 Python
我正在使用 beautifulsoup 从页面中获取所有链接。我的代码是: import requests from bs4 import BeautifulSoup url = 'http://ww
我正在使用react-beautiful-dnd版本8.0.5(最新)并尝试渲染可重组列表,但我不断收到此错误: Warning: React.createElement: type is inval
我在将组件放入应用程序的下一个列表区域时遇到困难。我可以在父列中完美地拖放和排序,但无法将组件放在其他地方。这是我的 onDragEnd 函数中的代码: onDragEnd = result =>
发生的情况是,当我在一列中有多个项目并尝试拖动其中一个时,只显示一个项目,并且根据发现的经验教训 here我应该处于可以移动同一列内的项目但不能移动的位置。在 React 开发工具中,state 和
我正在尝试根据部分属性值来识别 html 文档中的标签。 例如,如果我有一个 Beautifulsoup 对象: import bs4 as BeautifulSoup r = requests.ge
Показать телефон 如何在 Beautiful Soup 中找到上述元素? 我尝试了以下方法,但没有奏效: show = soup.find('div', {'class': 'acti
我如何获得结果网址:https://www.sec.gov/Archives/edgar/data/1633917/000163391718000094/0001633917-18-000094-in
我是 python 新手,尝试从页面中提取表格,但无法使用 BS4 找到该表格。你能告诉我我哪里出错了吗? import requests from bs4 import BeautifulSoup
我是一名优秀的程序员,十分优秀!