I am trying to extract the content of a single “value” attribute in a specific “input” tag on a webpage. I use the following code:
JavaScript
x
14
14
1
import urllib
2
f = urllib.urlopen("http://58.68.130.147")
3
s = f.read()
4
f.close()
5
6
from BeautifulSoup import BeautifulStoneSoup
7
soup = BeautifulStoneSoup(s)
8
9
inputTag = soup.findAll(attrs={"name" : "stainfo"})
10
11
output = inputTag['value']
12
13
print str(output)
14
I get TypeError: list indices must be integers, not str
Even though, from the Beautifulsoup documentation, I understand that strings should not be a problem here… but I am no specialist, and I may have misunderstood.
Any suggestion is greatly appreciated!
Advertisement
Answer
.find_all()
returns list of all found elements, so:
JavaScript
1
2
1
input_tag = soup.find_all(attrs={"name" : "stainfo"})
2
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
JavaScript
1
2
1
output = input_tag[0]['value']
2
or use .find()
method which returns only one (first) found element:
JavaScript
1
3
1
input_tag = soup.find(attrs={"name": "stainfo"})
2
output = input_tag['value']
3