Extracting an attribute value with beautifulsoup
.find_all()
returns list of all found elements, so:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
output = input_tag[0]['value']
or use .find()
method which returns only one (first) found element:
input_tag = soup.find(attrs={"name": "stainfo"})output = input_tag['value']
In Python 3.x
, simply use get(attr_name)
on your tag object that you get using find_all
:
xmlData = Nonewith open('conf//test1.xml', 'r') as xmlFile: xmlData = xmlFile.read()xmlDecoded = xmlDataxmlSoup = BeautifulSoup(xmlData, 'html.parser')repElemList = xmlSoup.find_all('repeatingelement')for repElem in repElemList: print("Processing repElem...") repElemID = repElem.get('id') repElemName = repElem.get('name') print("Attribute id = %s" % repElemID) print("Attribute name = %s" % repElemName)
against XML file conf//test1.xml
that looks like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root> <singleElement> <subElementX>XYZ</subElementX> </singleElement> <repeatingElement id="11" name="Joe"/> <repeatingElement id="12" name="Mary"/></root>
prints:
Processing repElem...Attribute id = 11Attribute name = JoeProcessing repElem...Attribute id = 12Attribute name = Mary
If you want to retrieve multiple values of attributes from the source above, you can use findAll
and a list comprehension to get everything you need:
import urllibf = urllib.urlopen("http://58.68.130.147")s = f.read()f.close()from BeautifulSoup import BeautifulStoneSoupsoup = BeautifulStoneSoup(s)inputTags = soup.findAll(attrs={"name" : "stainfo"})### You may be able to do findAll("input", attrs={"name" : "stainfo"})output = [x["stainfo"] for x in inputTags]print output### This will print a list of the values.