2014-11-25 91 views
1

我需要從鏈接()標記中獲取「href」屬性。BeautifulSoup:TypeError:'NoneType'object is not subcriptable

我跑

label_tag = row.find(class_='Label') 
print(label_tag) 

和我(對不起,我不能顯示隱私的原因鏈接和文本)

<a class="Label" href="_link_">_text_</a> 

<class 'bs4.element.Tag'> 

但當我跑(如BeautifulSoup getting href所示)

tag_link = label_tag['href'] 
print(tag_link) 

我想下面的錯誤(在第一個命令)

TypeError: 'NoneType' object is not subscriptable 

任何線索? 在此先感謝

[解決]編輯:我犯了一個錯誤(遍歷異構結構元素)

+0

你能表現出此刻的你有完整的代碼嗎?謝謝。 – alecxe 2014-11-25 15:31:17

回答

5

我的猜測是,label_tag實際上沒有返回湯,你正在尋找的一部分對於。這個小例子工程:

import bs4 
text = '''<a class="Label" href="_link_">_text_</a>''' 
soup = bs4.BeautifulSoup(text) 
link = soup.find("a",{"class":"Label"}) 
print (link["href"]) 

輸出:

_link_ 
+0

你是絕對正確的。我犯了一個錯誤(循環不同結構的元素)。現在它工作。不管怎麼說,還是要謝謝你 – dragonmnl 2014-11-25 15:48:09