Python: BeautifulSoup - get an attribute value based on the name attribute

后端 未结 7 1791
抹茶落季
抹茶落季 2020-11-27 10:38

I want to print an attribute value based on its name, take for example


I want to do something

7条回答
  •  眼角桃花
    2020-11-27 11:17

    6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:

    Ayr
    

    I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.

    How I managed to do it eventually:

    >>> from bs4 import BeautifulSoup as bs
    
    >>> soup = bs('Ayr', 'html.parser')
    >>> my_attributes = soup.find().attrs
    >>> my_attributes
    {u'property': u'addressLocality'}
    

    As it's a dict, you can then also use keys and 'values'

    >>> my_attributes.keys()
    [u'property']
    >>> my_attributes.values()
    [u'addressLocality']
    

    Hopefully it helps someone else!

提交回复
热议问题