Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeautifulSoup: TypeError: 'NoneType' object is not subscriptable

I need take "href" attribute from a link (a) tag.

I run

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

and I get (sorry, I can't show link and text for privacy reasons)

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

of type

<class 'bs4.element.Tag'>

but when I run (as shown at BeautifulSoup getting href )

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

I guess the following error (on first command)

TypeError: 'NoneType' object is not subscriptable

Any clue? Thanks in advance

[SOLVED] EDIT: I was making a mistake (looping over elements with heterogeneous structure)

like image 294
dragonmnl Avatar asked Oct 15 '25 08:10

dragonmnl


1 Answers

My guess is that label_tag isn't actually returning the part of the soup you are looking for. This minimal example works:

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

Output:

_link_
like image 66
Hooked Avatar answered Oct 16 '25 23:10

Hooked