从存储的 .html 页面中提取新闻文章内容

Extract News article content from stored .html pages

我正在阅读 html 文件中的文本并进行一些分析。这些 .html 文件是新闻文章。

代码:

 html = open(filepath,'r').read()
 raw = nltk.clean_html(html)  
 raw.unidecode(item.decode('utf8'))

现在我只想要文章内容,而不是广告、标题等文本的其余部分。如何在 python 中相对准确地做到这一点?

我知道 Jsoup(a java api) 和 bolier but I want to do so in python. I could find some techniques using bs4 等工具,但仅限于一种类型的页面。我有来自众多来源的新闻页面。此外,缺少任何示例代码示例。

我正在 python.

中寻找与 http://www.psl.cs.columbia.edu/wp-content/uploads/2011/03/3463-WWWJ.pdf 完全相同的东西

编辑: 为了更好的理解,请编写示例代码提取以下内容 link http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general

您可以使用 htmllib or HTMLParser 您可以使用这些来解析您的 html 文件

from HTMLParser import HTMLParser

# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Encountered a start tag:", tag
    def handle_endtag(self, tag):
        print "Encountered an end tag :", tag
    def handle_data(self, data):
        print "Encountered some data  :", data

# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')

取自 HTMLParser 页面的代码示例

通过直接访问页面来尝试这样的事情:

##Import modules
from bs4 import BeautifulSoup
import urllib2


##Grab the page
url = http://www.example.com
req = urllib2.Request(url)
page = urllib2.urlopen(req)
content = page.read()
page.close()  

##Prepare
soup = BeautifulSoup(content) 

##Parse (a table, for example)

for link in soup.find_all("table",{"class":"myClass"}):
    ...do something...
pass

如果要加载文件,只需将抓取页面的部分替换为文件即可。在此处了解更多信息:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

在 Python 中组织 html-scaraping 的方法有很多。如其他答案所述,工具 #1 是 BeautifulSoup,但还有其他工具:

这里有有用的资源:

没有通用的查找文章内容的方法。 HTML5 有文章标签,提示正文,也许可以调整对特定发布系统页面的抓取,但没有通用的方法来准确猜测文本位置。 (理论上,机器可以通过查看多篇结构相同但内容不同的文章来推断页面结构,但这可能超出了此处的范围。)

另外 Web scraping with Python 可能相关。

纽约时报的 Pyquery 示例:

from pyquery import PyQuery as pq
url = 'http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general'
d = pq(url=url)
text = d('.story-content').text()

Python 中也有这方面的库 :)

由于您提到了 Java,因此有一个 Python 样板管道包装器,允许您直接在 python 脚本中使用它:https://github.com/misja/python-boilerpipe

如果你想使用纯 python 库,有 2 个选项:

https://github.com/buriy/python-readability

https://github.com/grangier/python-goose

在这两者中,我更喜欢 Goose,但请注意,它的最新版本有时会由于某种原因无法提取文本(我的建议是目前使用版本 1.0.22)

编辑:这是使用 Goose 的示例代码:

from goose import Goose
from requests import get

response = get('http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&ref=general')
extractor = Goose()
article = extractor.extract(raw_html=response.content)
text = article.cleaned_text

Newspaper越来越流行了,我只是粗略地用了一下,但看起来不错。只有 Python 3 个。

快速入门仅显示从 URL 加载,但您可以 load from a HTML string 使用:

import newspaper

# LOAD HTML INTO STRING FROM FILE...

article = newspaper.Article('') # STRING REQUIRED AS `url` ARGUMENT BUT NOT USED
article.set_html(html)

我强烈推荐使用 Trafilatura。超级容易实施,而且速度很快!

import trafilatura
url = 'www.example.com'
downloaded = trafilatura.fetch_url(url)
article_content = trafilatura.extract(downloaded)

给出:

'This domain is for use in illustrative examples in documents. You may use this\ndomain in literature without prior coordination or asking for permission.\nMore information...'

你也可以直接给它HTML,像这样:

trafilatura_text = trafilatura.extract(html, include_comments=False)

如果您对更多字段感兴趣,例如作者/出版日期,您可以使用 bare_extraction:

import trafilatura
url = 'www.example.com'
downloaded = trafilatura.fetch_url(url)
trafilatura.bare_extraction(downloaded, include_links=True)

哪个会给你:

{'title': 'Example Domain',
 'author': None,
 'url': None,
 'hostname': None,
 'description': None,
 'sitename': None,
 'date': None,
 'categories': [],
 'tags': [],
 'fingerprint': None,
 'id': None,
 'license': None,
 'body': None,
 'comments': '',
 'commentsbody': None,
 'raw_text': None,
 'text': 'This domain is for use in illustrative examples in documents. You may use this\ndomain in literature without prior coordination or asking for permission.\nMore information...'}