0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Beautiful Soup の Tag に対する [] と in の挙動

Posted at

beautifulsoup4==4.12.3 で動作確認しています。

まとめ

bs4.element.Tag オブジェクト x に対し、 x[attr_name] は「x の属性 attr_name の値」、y in x は「HTML 要素 yx 直下にあるか」を意味する ([]in で対象が異なる)。

スニペット

from bs4 import BeautifulSoup

text = '<div id="hoge"><p>Apple</p>Banana</div>'
soup = BeautifulSoup(text, 'html.parser')
div = soup.find('div')
p = soup.find('p')

# 1
assert div['id'] == 'hoge'
# 2
assert 'id' not in div
# 3
assert 'id' in div.attrs
assert type(div.attrs) is dict
# 4
assert p in div
assert 'Apple' not in div
assert 'Banana' in div
assert type(div.contents) is list
  1. bs4.element.Tag オブジェクトは角括弧で属性にアクセスできる。
  2. じゃあ in 演算子で属性の有無を判定できるかというとできない。
  3. 属性の有無を判定するには .attrs メンバに in 演算子を適用する (.attrs メンバからそのタグの属性の辞書にアクセスできる)。
  4. bs4.element.Tag オブジェクトに直接 in 演算子を適用したときに判定できるのは直下の要素の有無である (in 演算子は直下の要素のリスト .contents に対する in として実装されているため)。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?