(4)Beautiful Soupライブラリを使い始める
BeautifulSoupライブラリの公式ドキュメント
(1)Beautiful Soupライブラリの基本要素
<p class="title">...</p>
<p>..</p> :标签 Tag
p :名称 Name (成对出现)
class='title':属性 Attributes (0个或多个)
from bs4 import BeautifulSoup
soup1 = BeautifulSoup("<html>data</html>","html.parser")
soup2 = BeautifulSoup("open("D://demo.html")","html.parser")
(2)BeautifulSoupライブラリパーサー
パーサー |
使い方 |
状態 |
bs4のHTMLパーサー |
BeautifulSoup(「mk」、「html.parser」) |
bs4ライブラリをインストールする |
lxml HTMLパーサー |
BeautifulSoup(“ mk”、“ lxml”) |
pip install lxml |
lxmlのXMLパーサー |
BeautifulSoup(“ mk”、“ xml”) |
pip install lxml |
html5libのパーサー |
BeautifulSoup(“ mk”、“ html5lib”) |
pipインストールhtml5lib |
(3)BeautifulSoupクラスの基本要素
例:<p class="title">...</p>
基本要素 |
解説 |
鬼ごっこ |
<>と</>で始まる、情報の編成の最も基本的な単位であるタグは、開始と終了を示します |
名前 |
ラベルの名前、 … 名前は「p」で、形式は.nameです。 |
の属性 |
辞書形式で編成されたタグ属性、形式:.attrs |
NavigableString |
タグ内の非属性文字列、<> ... </>内の文字列、形式:.string |
コメント |
ラベル内の文字列のコメント部分、特別なタイプのコメント |
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,"html.parser")
soup.title
soup.a
soup.find_all('a')
soup.get_text()
soup.a.name
soup.a.parent.name
soup.a.parent.parent.name
tag.attrs
tag.attrs['class']
soup.a.string
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>","html.parser")
newsoup.b.string
newsoup.p.string
(4)bs4ライブラリに基づくHTMLコンテンツトラバーサルメソッド
1.タグツリーの下向きトラバーサル
の属性 |
解説 |
.contents |
子ノードのリスト、すべての息子ノードをリストに保存します |
。子供達 |
.contentsに類似した子ノードの反復タイプは、息子ノードをループするために使用されます |
。子孫 |
ループトラバーサルのためのすべての子孫ノードを含む子孫ノードの反復タイプ |
soup = BeautifulSoup(demo, "html.parser")
soup.head
soup.head.contents
soup.body.contents
len(soup.body.contents)
soup.body.contents[1]
for child in soup.body.children:
print(child)
for child in soup.body.descendants:
print(children)
2.タグツリーのアップリンクトラバーサル
の属性 |
解説 |
。親 |
ノードの親ラベル |
。親 |
祖先ノードをループするために使用されるノード祖先ラベルの反復タイプ |
soup = BeautifulSoup(demo, "html.parser")
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
3.ラベルツリーの並列走査
の属性 |
解説 |
.next_sibling |
次の並列ノードラベルをHTMLテキスト順に返します |
.previous_sibling |
前の並列ノードラベルをHTMLテキスト順に返します |
.next_siblings |
反復タイプ。後続の並列ノードタグをHTMLテキスト順に返します |
.previous_siblings |
反復タイプ。以前の並列ノードタグをHTMLテキスト順に返します |
for sibling in soup.a.next_sibling:
print(sibling)
for sibling in soup.a.previous_sibling:
print(sibling)
(5)bs4ライブラリに基づくHTML形式の出力
soup.prettify()
soup.a.prettify()
ノードタグ|
| .previous_sibling |前の並列
ノードタグをHTMLテキスト順で返す| | .next_siblings |反復タイプ、後続の並列ノードタグをHTMLテキスト順で返す|
| .previous_siblings |反復タイプ、HTMLテキスト順で返す前の並列ノードラベル|
[外部リンク画像を転送しています...(img-mxfhEfda-1586863050051)]
for sibling in soup.a.next_sibling:
print(sibling)
for sibling in soup.a.previous_sibling:
print(sibling)
(5)bs4ライブラリに基づくHTML形式の出力
soup.prettify()
soup.a.prettify()