2013-10-24 76 views
2
from bs4 import BeautifulSoup 

source_code = """<a href="#" name="One"></a> 
       <a href="#" name="Two"></a>""" 

soup = BeautifulSoup(source_code) 

print soup.a['name'] #prints 'One' 

使用BeautifulSoup,我可以抓住的第一個名字屬性,是one,但我不知道我怎麼可以打印第二,這是Two獲得「名」與美麗的湯屬性

任何人都能夠幫幫我?

回答

5

您應該閱讀the documentation。您可以看到soup.find_all返回一個列表 ,因此您可以遍歷該列表,併爲每個元素提取您正在查找的標記。所以,你應該這樣做(這裏未測試):

from bs4 import BeautifulSoup 
soup = BeautifulSoup(source_code) 
for item in soup.find_all('a'): 
    print item['name'] 
1

要獲得除第一個以外的任何a子元素,請使用find_all。對於第二a標籤:

print soup.find_all('a', recursive=False)[1]['name'] 

爲了保持在同一水平上,避免了深刻的搜索,傳遞參數:recursive=False

+0

感謝堆! – vjgaero

+0

如果我用INPUT而不是A來嘗試這個,我會得到一個超出範圍的錯誤。 這是爲什麼? – vjgaero

+0

Upvote for recursive = False。很高興知道。 – Josh

1

這會給你「一」的所有標籤:

>>> from BeautifulSoup import BeautifulSoup 
>>> aTags = BeautifulSoup(source_code).findAll('a') 
>>> for tag in aTags: print tag["name"] 
... 
One 
Two 
+0

@vjgaero如果它對你有用,請通過[接受](http://stackoverflow.com/help/accepted-answer)來回答問題。 – Sudipta