首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python HTML解析,获取带有其值的标记名。

问Python HTML解析,获取带有其值的标记名。
EN

Stack Overflow用户
提问于 2014-02-25 07:58:59
回答 1查看 2.4K关注 0票数 4

我用的是Python的漂亮汤。

是否有一种方法可以获得具有其值的属性名,如:

name=title value=This是标题

name=link值=./style.css

soup.html.head=

代码语言:javascript
复制
<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"/>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-25 08:01:50

使用.text或.string属性获取元素的文本内容。

使用.get('attrname')或['attrname']获取属性值。

代码语言:javascript
复制
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'])) # <----

产出:

代码语言:javascript
复制
name=title value= This is title
name=link value=.../style.css

根据OP的评论更新:

代码语言:javascript
复制
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)))

产出:与上述相同

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22007948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档