2012-05-29 104 views
1

我試圖使用BeautifulSoup,所以得到一個HTML標籤列表,然後檢查他們是否有一個名稱屬性,然後返回該屬性值。請參閱我的代碼:BeautifulSoup,獲取標籤列表並獲取屬性值

soup = BeautifulSoup(html) #assume html contains <div> tags with a name attribute 
nameTags = soup.findAll('name') 
for n in nameTags: 
    if n.has_key('name'): 
     #get the value of the name attribute 

我的問題是如何獲取name屬性的值?

由於提前 露絲

回答

5

使用下面的代碼,它應該工作

nameTags = soup.findAll('div',{"name":True}) 
for n in nameTags: 
    # Do your processing 
+0

謝謝Ramesh,您的上述代碼可以工作,但我想知道如何獲取屬性的值 – Ruth

1

謝謝大家想通了

n['name'] 
1

以供將來參考,這裏是代碼用作單個答案:

soup = BeautifulSoup(html) 
nameTags = soup.findAll('div',{"name":True}) 
for n in nameTags: 
    name = n['name'] 
    # Do your processing 

傳遞{"name":True}的第二個參數會將結果限制爲div具有name屬性的標籤。如果您正在尋找具有name標記的特定值的標記,則可以通過{"name":"specificNameValue"}