从bs4.element.Tag获取项目 [英] Get item from bs4.element.Tag

查看:45
本文介绍了从bs4.element.Tag获取项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为bs4.element.Tag的元素

I have element with type bs4.element.Tag

<a class="nav-link match-link-stats" href="/football/matches/match867851_Kalteng_Putra-Arema-online/" title="Stat"><i class="icon-match-link"></i></a>

我想从该元素中获取"/football/matches/match867851_Kalteng_Putra-Arema-online/".怎么做?

And I want to get "/football/matches/match867851_Kalteng_Putra-Arema-online/" from this element. How to do it?

推荐答案

此答案假定您已经具有 Tag 元素作为对象.如果没有,请使用KunduK的答案.

This answer assumes you already have the Tag element as an object. If not, use KunduK's answer.

您可以使用 tag.get('href') tag ['href'] :

>>> tag.get('href')
'/football/matches/match867851_Kalteng_Putra-Arema-online/'
>>> tag['href']
'/football/matches/match867851_Kalteng_Putra-Arema-online/'

区别在于,如果属性不存在, tag.get('href')将返回None,而 tag ['href'] 将引发一个在这种情况下为 KeyError .这与 dict 中的行为相同.

The difference is that tag.get('href') will return None if the attribute doesn't exist, while tag['href'] will raise a KeyError in that case. That's the same behavior as in a dict.

完整示例:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<a class="nav-link match-link-stats" href="/football/matches/match867851_Kalteng_Putra-Arema-online/" title="Stat"><i class="icon-match-link"></i></a>')
>>> tag = soup.find('a')
>>> type(tag)
<class 'bs4.element.Tag'>
>>> tag.get('href')
'/football/matches/match867851_Kalteng_Putra-Arema-online/'
>>> tag['href']
'/football/matches/match867851_Kalteng_Putra-Arema-online/'

这篇关于从bs4.element.Tag获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆