2009-10-01 55 views
10

我正在尝试使用BeautifulSoup来解析DOM树并提取作者的名字。下面是一段HTML代码,用于显示我将要扫描的代码的结构。使用Python中的BeautifulSoup解析出数据

<html> 
<body> 
<div class="list-authors"> 
<span class="descriptor">Authors:</span> 
<a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1">Dacheng Lin</a>, 
<a href="/find/astro-ph/1/au:+Remillard_R/0/1/0/all/0/1">Ronald A. Remillard</a>, 
<a href="/find/astro-ph/1/au:+Homan_J/0/1/0/all/0/1">Jeroen Homan</a> 
</div> 
<div class="list-authors"> 
<span class="descriptor">Authors:</span> 
<a href="/find/astro-ph/1/au:+Kosovichev_A/0/1/0/all/0/1">A.G. Kosovichev</a> 
</div> 

<!--There are many other div tags with this structure--> 
</body> 
</html> 

我的困惑的一点是,当我这样做soup.find,找到div标签是我在寻找的第一次出现。之后,我搜索所有'a'链接标签。在这个阶段,我如何从每个链接标签中提取作者姓名并将其打印出来?有没有办法使用BeautifulSoup来做,还是我需要使用正则表达式?我如何继续迭代其他每个div标签并提取作者名称?

import re 
import urllib2,sys 
from BeautifulSoup import BeautifulSoup, NavigableString 
html = urllib2.urlopen(address).read() 
    soup = BeautifulSoup(html) 

    try: 

     authordiv = soup.find('div', attrs={'class': 'list-authors'}) 
     links=tds.findAll('a') 


     for link in links: 
      print ''.join(link[0].contents) 

     #Iterate through entire page and print authors 


    except IOError: 
     print 'IO error' 

回答

12

只是使用的findAll为div的链接您soup.findAll链接

为authordiv做( '格',ATTRS = { '类': '列表作者'}):

1

由于link已经从一个可迭代拍摄,你不需要分类指数link - 你可以做link.contents[0]

print link.contents[0]与两个独立<div class="list-authors">产量新的例子:

Dacheng Lin 
Ronald A. Remillard 
Jeroen Homan 
A.G. Kosovichev 

所以我不知道我的理解对搜索其它的div的评论。如果他们是不同的班级,你需要单独做soup.findsoup.findAll,或者只是修改你的第一个soup.find

+1

而如果有更多的div标签,我该如何迭代这些标签? – GobiasKoffi 2009-10-01 03:24:44

+0

如果您通过CSS类搜索,则会获取元素列表,您可以使用for循环进行迭代(请参阅:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-类)。做一些类似于:'authordiv = soup.find('div',class_ ='list-authors')'。 – eNord9 2014-09-01 16:46:09