从BeautifulSoup文章中获取文本

时间:2013-12-05 13:06:37

标签: python beautifulsoup

我有一个简单的python程序,它在url中搜索关键字并返回true或false。我想修改它,所以我只搜索文章,而不是标题,而不是网页或广告或其他文章等其他东西。我有数百个URL检查,他们没有;有相同的风格(我猜,没有检查过它们,但有点明显)。如果可能的话,我怎么能这样做呢?第一次使用BeautifulSoup。

这是我现在使用的

import re
import sys
from BeautifulSoup import BeautifulSoup
import urllib2

#argecho.py

content = urllib2.open(sys.argv[1]).read()

print sys.argv[2] in content # -> True

我发送url和关键字作为参数,因为我有另一个脚本为数百个网址调用它。

3 个答案:

答案 0 :(得分:2)

没有简单的方法从网页中提取文章。您可以使用一些外部服务来提取Readabilitypython library等内容

答案 1 :(得分:2)

BeautifulSoup本身无法从“文章”中提取文本,因为 的文章是完全主观的,并且会从一个站点更改为下一个站点。您需要为每个站点编写不同的解析器。

我的建议是使用继承对此进行建模:

class Webpage(object):
    def __init__(self, html_string):
        self.html= BeautifulSoup(html_string)
    def getArticleText(self):
        raise NotImplemented

class NewYorkTimesPage(Webpage):
    def getArticleText(self):
        return self.html.find(...)

答案 2 :(得分:2)

通过将sys.argv[2]转换为正则表达式,您可以使用BeautifulSoup在 正文文本中搜索文本:

import sys
from bs4 import BeautifulSoup
import urllib2
import re

response = urllib2.urlopen(sys.argv[1])
soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))
text_pattern = re.compile(re.escape(sys.argv[2]))

if soup.find('body').find(text=text_pattern):
    print 'Found the text in the page')

但是,要进一步缩小范围以排除导航,页脚等,您需要应用一些启发式方法。每个站点都不同,并且检测页面的哪个部分构成主要文本并不是一项简单的任务。

您可能想要查看Readability API,而不是重新发明那个轮子;他们已经建立了一个庞大的启发式库来为您解析网站的“主要”部分。