5

我正在尝试为各种科学期刊网站组合一个基本的 HTML 抓取工具,特别是尝试获取摘要或介绍性段落。

我目前正在研究的期刊是 Nature,我一直在使用的文章作为我的样本可以在http://www.nature.com/nature/journal/v463/n7284/abs/nature08715.html

但是,我无法从该页面中获取摘要。我正在搜索<p class="lead">...</p>标签之间的所有内容,但我似乎无法弄清楚如何隔离它们。我以为这会很简单

from BeautifulSoup import BeautifulSoup
import re
import urllib2

address="http://www.nature.com/nature/journal/v463/n7284/full/nature08715.html"
html = urllib2.urlopen(address).read()
soup = BeautifulSoup(html)

abstract = soup.find('p', attrs={'class' : 'lead'})
print abstract

使用 Python 2.5,BeautifulSoup 3.0.8,运行它返回“无”。我没有选择使用其他需要编译/安装的东西(比如 lxml)。BeautifulSoup 很困惑,还是我?

4

2 回答 2

5

该 html 格式非常错误,xml.dom.minidom 无法解析,BeautiFulSoup 解析也无法正常工作。

我删除了一些<!-- ... -->部分并用 BeautiFulSoup 再次解析,然后它看起来更好并且能够运行soup.find('p', attrs={'class' : 'lead'})

这是我尝试过的代码

>>> html =re.sub(re.compile("<!--.*?-->",re.DOTALL),"",html)
>>>
>>> soup=BeautifulSoup(html)
>>>
>>> soup.find('p', attrs={'class' : 'lead'})
<p class="lead">The class of exotic Jupiter-mass planets that orb  .....
于 2010-03-26T07:51:00.290 回答
2

这是获取摘要的非 BS 方式。

address="http://www.nature.com/nature/journal/v463/n7284/full/nature08715.html"
html = urllib2.urlopen(address).read()
for para in html.split("</p>"):
    if '<p class="lead">' in para:
        abstract=para.split('<p class="lead">')[1:][0]
        print ' '.join(abstract.split("\n"))
于 2010-03-26T08:03:01.783 回答