LoginSignup
4
2

More than 5 years have passed since last update.

bs4でHTMLタグを含む文字列を扱う時の挙動

Posted at

概要

  • bs4の文字列抽出の挙動についての実験

まとめ

  • soup.p.stringがNoneになるのはNavigableStringの仕様どおり
  • soupで読み込んだ時点で閉じタグがないタイプのタグは補完が行われていると思われる
    • たとえ<br>であっても。。

共通部分

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = """
<p>
  tanaka
  <br>
  tarou
  <br>
</p>
"""
soup = BeautifulSoup(html, 'html.parser')

やりたいこと

- 型はなんでもいいから"tanaka tarou"が取り出したい

抽出のための試行錯誤

- 実行結果の後にコマンドの形式で記載

最も単純なパターン

# None
print(soup.p.string)

stringsでループ

'''

  tanaka


  tarou



'''
for string in soup.p.strings:
    print(string)

brタグを除去

'''
<p>
  tanaka
  </p>
'''
# soup内のbrタグを全削除
[s.extract() for s in soup('br')]
print(soup.p)


'''

  tanaka

'''
print(soup.p.title)

さらに実験

  • soup上でご丁寧にbrの閉じタグが保管されていた。。。
'''
<br>
  tarou
  <br>
</br></br>
'''
print(soup.br.string)
4
2
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
4
2