我用的是Python的漂亮汤。
是否有一种方法可以获得具有其值的属性名,如:
name=title value=This是标题
name=link值=./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"/>发布于 2014-02-25 08:01:50
使用.text或.string属性获取元素的文本内容。
使用.get('attrname')或['attrname']获取属性值。
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'])) # <----产出:
name=title value= This is title
name=link value=.../style.css根据OP的评论更新:
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)))产出:与上述相同
https://stackoverflow.com/questions/22007948
复制相似问题