views:

172

answers:

1

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:

import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()

from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)

inputTag = soup.findAll(attrs={"name" : "stainfo"})

output = inputTag['value']

print str(output)

I get a 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 a no specialist and i may have misunderstood.

Any suggestion is greatly appreciated! Thanks in advance.

+3  A: 

.findAll() returns list of all found elements, so:

inputTag = soup.findAll(attrs={"name" : "stainfo"})

inputTag is a list (probably containing only one element). Depending on what you want exactly you either should do:

 output = inputTag[0]['value']

or use .find() method which returns only one (first) found element:

 inputTag = soup.find(attrs={"name": "stainfo"})
 output = inputTag['value']
Łukasz
Great stuff! Thanks. now i have a question about parsing the output which i a long bunch of non-ASCII chars but I will ask this in a separate question.
Barnabe
shouldn't the 'value' be accessed as per http://stackoverflow.com/questions/2616659/extracting-value-in-beautifulsoup . What makes the above code work in this case? I thought you would have to access the value by doing `output = inputTag[0].contents`
Seth