Get a list of tags and get the attribute values in BeautifulSoup

我们两清 提交于 2020-01-23 21:02:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!