1. BeautifulSoupの概要
BeautifulSoupはlxmlのようなHTML / XMLパーサーです。その主な機能はHTML / XMLデータを解析して抽出することです
lxmlとは異なり、BeautifulSoupはHTML DOM(Document Object Model)に基づいており、ドキュメント全体をロードしてDOMツリー全体を解析するため、時間とメモリのオーバーヘッドがはるかに大きくなり、すべてのパフォーマンスがlxmlよりも低くなります。
1.1分析ツールの比較:
1.2使いやすい
パーサーがない場合、ドキュメントの解析時にエラーは報告されませんが、警告が表示されます。
警告内容:
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
大まかな意味は、指定されたパーサーがないため、デフォルトで最適なパーサーlxmlが使用されますが、異なるシステムおよび環境で実行する場合は、異なるパーサーを使用するため、結果は必ずしも同じではありません。 。
公式の推奨はlxmlです。
パーサーを使用した後、htmlドキュメントが不完全であっても、パース時にlxmlが不完全な部分を埋めることがわかりました。これは、上記の画像のコンテンツです。
通常、html形式には、各モジュールを区別するための特定のインデントがあります。この操作は、BeautifulSoupでの実装も非常に簡単です。スープでprettify()関数を呼び出すだけで済みます。結果は次のとおりです。
2. 4つの共通オブジェクト
2.1タグ
Tagはhtmlのタグです。使用する場合は、直接soupを使用します。タグ名を追加して、タグの内容を見つけます。
注意:タグで見つかったタグは、すべてのコンテンツの要件を満たす最初のタグです。
soup = BeautifulSoup(html, 'lxml')
print(soup.p)
print(type(soup.p))#查看类型
#两个重要属性name, attrs
print(soup.head.name)
print(soup.p.name)
print(soup.p.attrs)
print(soup.p['class'])
print(soup.p.get('class'))
soup.p['class'] = 'new'
print(soup.p.attrs)
結果:
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<class 'bs4.element.Tag'>
head
p
{'class': ['title'], 'name': 'dromouse'}
['title']
['title']
{'class': 'new', 'name': 'dromouse'}
2.2 NavigableString
NavigableStringタグは、タグ内のコンテンツテキストを取得できます。
または、上記の例に従って、NavigableStringモジュールをインポートして使用します。
2.3 BeautifulSoup
BeautifulSoupオブジェクトは、ドキュメントのコンテンツ全体を表します。ほとんどの場合、これはTagオブジェクトと見なすことができます。BeautifulSoupは、ドキュメントツリーをトラバースし、ドキュメントツリーを検索するほとんどのメソッドをサポートしています。
BeautifulSoupソースコードのTagから継承されます。
2.3.1ドキュメントツリーをトラバースする
- コンテンツはすべての子ノードのリストを返します
- childrenはすべての子ノードのイテレータを返します
from bs4.element import Comment
head_tag = BeautifulSoup(html, 'lxml')
print(head_tag.contents) #返回时list
print(head_tag.children)
for i in head_tag.children:
print(i)
- 文字列:タグに複数の文字列が含まれている場合は、.stringを使用してループで取得し、ジェネレータに戻ることができます
for string in soup.strings:
print(string)
print(repr(string))
The Dormouse's story
"The Dormouse's story"
'\n'
'\n'
The Dormouse's story
"The Dormouse's story"
'\n'
Once upon a time there were three little sisters; and their names were
'Once upon a time there were three little sisters; and their names were\n'
,
',\n'
Lacie
'Lacie'
and
' and\n'
Tillie
'Tillie'
;
and they lived at the bottom of a well.
';\nand they lived at the bottom of a well.'
'\n'
...
'...'
'\n'
'\n'
Process finished with exit code 0
- stripped_string:.stripped_stringsは、出力文字列の余分な空白コンテンツまたは空白行を削除して、ジェネレーターに戻ることができます
for string in soup.stripped_strings:
print(string)
# print(repr(string))
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
,
Lacie
and
Tillie
;
and they lived at the bottom of a well.
...
Process finished with exit code 0
-
get_text:ラベルの子孫の非ラベル文字列を取得し、通常の文字列として返します
2.3.2文書ツリーの検索
詳細については、次のブログを参照してください。
https://blog.csdn.net/weixin_44566432/article/details/108664325
2.4コメント
コメントオブジェクトは特別なタイプのNavigableStringオブジェクトです