Python HTML parse, getting tag name with its value

beautifulsoup, python, python-2.7

Solution

Use `.text` or `.string` attribute to get text content of the element.

Use `.get('attrname')` or `['attrname']` to get attribute value.

html = '''
<head>
    <meta content="all" name="audience"/>
    <meta content="2006-2013 webrazzi.com." name="copyright"/>
    <title> This is title</title>
    <link href=".../style.css" media="screen" rel="stylesheet" type="text/css"/>
</head>
'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print('name={} value={}'.format('title', soup.title.text))  # <----
print('name={} value={}'.format('link', soup.link['href'])) # <----

output:

name=title value= This is title
name=link value=.../style.css

UPDATE according to the OP's comment:

def get_text(el): return el.text
def get_href(el): return el['href']

# map tag names to functions (what to retrieve from the tag)
what_todo = {
    'title': get_text,
    'link': get_href,
}
for el in soup.select('head *'): # To retrieve all children inside `head`
    f = what_todo.get(el.name)
    if not f: # skip non-title, non-link tags.
        continue
    print('name={} value={}'.format(el.name, f(el)))

output: same as above

Problem

I'm using beautifulsoup at Python. Is there a way to get property name with its value like: name=title value=This is title name=link value=.../style.css soup.html.head= ``` <meta content="all" name="audience"/> <meta content="2006-2013 webrazzi.com." name="copyright"/> <title> This is title</title> <link href=".../style.css" media="screen" rel="stylesheet" type="text/css"/> ```

Original source