【发布时间】:2011-02-28 00:07:42
【问题描述】:
我正在寻找一个 html 页面并仅提取该页面上的纯文本。任何人都知道在python中做到这一点的好方法吗?
我想从字面上删除所有内容,只留下文章的文本以及标签之间的其他文本。 JS、css等……没了
谢谢!
【问题讨论】:
标签: python
我正在寻找一个 html 页面并仅提取该页面上的纯文本。任何人都知道在python中做到这一点的好方法吗?
我想从字面上删除所有内容,只留下文章的文本以及标签之间的其他文本。 JS、css等……没了
谢谢!
【问题讨论】:
标签: python
这里的第一个答案不会删除页面中的 CSS 或 JavaScript 标记的正文(未链接)。这可能会更接近:
def stripTags(text):
scripts = re.compile(r'<script.*?/script>')
css = re.compile(r'<style.*?/style>')
tags = re.compile(r'<.*?>')
text = scripts.sub('', text)
text = css.sub('', text)
text = tags.sub('', text)
return text
【讨论】:
这是我发现的剥离 CSS 和 JavaScript 最干净、最简单的解决方案:
''.join(BeautifulSoup(content).findAll(text=lambda text:
text.parent.name != "script" and
text.parent.name != "style"))
【讨论】:
我也会推荐 BeautifulSoup,但我会建议使用类似 this question 的答案的内容,我将在此处复制给那些不想看那里的人:
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element)):
return False
return True
visible_texts = filter(visible, texts)
例如,我在此页面上尝试过,效果很好。
【讨论】:
lxml.html 模块值得考虑。但是,删除 CSS 和 JavaScript 需要花费一些时间:
def stripsource(page):
from lxml import html
source = html.fromstring(page)
for item in source.xpath("//style|//script|//comment()"):
item.getparent().remove(item)
for line in source.itertext():
if line.strip():
yield line
产生的行可以简单地连接,但这可能会丢失重要的 单词边界,如果空格生成周围没有任何空格 标签。
您可能还想仅迭代 <body> 标记,具体取决于您的要求。
【讨论】:
你可以试试相当优秀的Beautiful Soup
f = open("my_source.html","r")
s = f.read()
f.close()
soup = BeautifulSoup.BeautifulSoup(s)
txt = soup.body.getText()
但请注意:您从任何解析尝试中得到的结果都将受到“错误”的影响。糟糕的 HTML、糟糕的解析和一般的意外输出。如果您的源文档众所周知并且呈现良好,那么您应该没问题,或者至少能够解决其中的特质,但如果它只是“在互联网上”发现的一般东西,那么期待各种奇怪和奇妙的异常值。
【讨论】:
根据here:
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
正如他在文章中所说,“需要导入 re 模块才能使用正则表达式。”
【讨论】: