2009-10-01 61 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