>>> s = bs4.BeautifulSoup('<p foo="bar" class="ic">baz')
>>> s.get('foo')
>>> s.p.get('foo')
'bar'
>>> s.p.attrs
{'foo': 'bar', 'class': ['ic']}
如何檢查一個
Tag
實體是否有某個特定屬性
要檢查一個
Tag
實體
t
的HTML 屬性是否包括一個名稱叫做
'foo'
的,請
別
使用
if 'foo' in t:
,
Tag
實體上的
in
運算
子會在
Tag
的子節點中查找,而
非
它的屬性中。取而代之,
請使用
if 'foo' in t.attrs:
或
if t.has_attr('foo'):
。
當你有
NavigableString
的一個實體,你經常會想要存取它所含有的實際
文字字串;當你有
Tag
的一個實體,你可能會想要存取它含有的唯一字串
(unique string),或者,如果它含有多個的話,存取它們全部,可能還要
剝除圍住它們的任何空白。這裡是它們的做法。
取得一個實際的字串
如果你有一個
NavigableString
實體
s
,而你需要儲藏或處理它某處的文
字,而不想巡覽它,就呼叫
str(s)
(或在v2中,
unicode(s)
)。或者,
使用
s.encode(codec='utf8') ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.