让BeautifulSoup查找特定的<p>

6 投票
3 回答
12704 浏览
提问于 2025-04-15 20:52

我正在尝试制作一个简单的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)。是BeautifulSoup搞混了,还是我搞错了?

3 个回答

0
  to_p_tag = soup.findAll('p', class_='lead')

  if(len(to_p_tag) == 0):
    print("<p class='lead' /> not found")
  else:
    for p in to_p_tag:
      recursively_translate(translator, p, input_lang)
    # translated_p = translator.translate(to_p_tag.text, dest=input_lang)
    # lxml1 = lxml1.replace(to_p_tag.text,translated_p.text)

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

2

这里有一个简单直接的方法来获取摘要。

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"))
4

这个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  .....

撰写回答