Reputation: 57
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'
Using BeautifulSoup, i can grab the first name attribute which is one
, but i am not sure how i can print the second, which is Two
Anyone able to help me out?
Upvotes: 2
Views: 5876
Reputation: 5452
You should read the documentation. There you can see that soup.find_all
returns a list
so you can iterate over the list and, for each element, extract the tag you are looking for. So you should do something like (not tested here):
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code)
for item in soup.find_all('a'):
print item['name']
Upvotes: 4
Reputation: 4971
This will give you all the tags of "a":
>>> from BeautifulSoup import BeautifulSoup
>>> aTags = BeautifulSoup(source_code).findAll('a')
>>> for tag in aTags: print tag["name"]
...
One
Two
Upvotes: 1
Reputation: 81432
To get any a
child element other than the first, use find_all
. For the second a
tag:
print soup.find_all('a', recursive=False)[1]['name']
To stay on the same level and avoid a deep search, pass the argument: recursive=False
Upvotes: 1