找到一个特定的<p>

2024-05-12 19:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为各种科学期刊网站构建一个基本的HTML刮板,特别是尝试获取摘要或介绍性段落。

我目前正在写的是《自然》杂志,而我作为样本使用的文章可以在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,运行此命令将返回“None”。我没有选择使用任何其他需要编译/安装的东西(比如lxml)。是美群迷茫了,还是我迷茫了?


Tags: importcomhttpaddresshtmlwwwurllib2class
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"))

这个html格式有点不正确,xml.dom.minidom无法解析,而且美化了组解析的效果。

我删除了一些<!-- ... -->部分,并使用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  .....

相关问题 更多 >