问题
I'm attempting to use BeautifulSoup so get a list of HTML <div> tags, then check if they have a name attribute and then return that attribute value. Please see my code:
soup = BeautifulSoup(html) #assume html contains <div> tags with a name attribute
nameTags = soup.findAll('name')
for n in nameTags:
if n.has_key('name'):
#get the value of the name attribute
My question is how do I get the value of the name attribute?
回答1:
Use the following code, it should work
nameTags = soup.findAll('div',{"name":True})
for n in nameTags:
# Do your processing
回答2:
Thank you all figured it out
n['name']
回答3:
For future reference, here is the code to use as a single answer:
soup = BeautifulSoup(html)
nameTags = soup.findAll('div',{"name":True})
for n in nameTags:
name = n['name']
# Do your processing
Passing a second argument of {"name":True} limits the results to div tags that have a name attribute. If you were looking for tags that had a specific value for the name tag, you could pass {"name":"specificNameValue"}
来源:https://stackoverflow.com/questions/10797741/get-a-list-of-tags-and-get-the-attribute-values-in-beautifulsoup