BeautifulSoup4ライブラリ
同様にlxmlの、美しいスープはまた、HTML / XMLパーサであると、主な機能は、HTML / XMLデータを解析して抽出する方法です。
lxmlの部分的にしかトラバーサル、そして美しいスープは、HTMLのDOM(Document Object Model)に基づいており、文書全体をロードします、全体のDOMツリーを解析し、そのパフォーマンスはlxmlのよりも低くなるので、時間とメモリのオーバーヘッドは、はるかに大きくなります。
HTMLを解析するためのBeautifulSoupは比較的簡単ですが、APIは非常にユーザーフレンドリーれている、HTMLパーサのPythonの標準ライブラリはまた、XMLパーサlxmlのをサポートし、CSSセレクタをサポートしています。
美しいスープ3の開発を停止している、我々は今、美しいスープ4を使用するプロジェクトをお勧めします。
インストールおよびドキュメント:
- インストール:
pip install bs4
。 - 中国のドキュメント:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
いくつかの主要な分析ツールの比較:
分析ツール | 解析スピード | 難易度の使用 |
---|---|---|
BeautifulSoup | 最も遅いです | 最も簡単な |
lxmlの | 速いです | シンプル |
定期的な | 最速 | 最も難しいです |
使用するのは簡単:
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#创建 Beautiful Soup 对象
# 使用lxml来进行解析 soup = BeautifulSoup(html,"lxml") print(soup.prettify())
四個の一般的に使用されるオブジェクト:
美しいスープ複雑なHTML文書は、各ノードがPythonオブジェクトで、複雑なツリー構造に変換し、すべてのオブジェクトは4種類に分類できます。
- タグ
- NavigatableString
- BeautifulSoup
- コメント
1.タグ:
タグ人気話すには、HTMLタグの1つです。次のようにサンプル・コードは次のとおりです。
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#创建 Beautiful Soup 对象
soup = BeautifulSoup(html,'lxml') print soup.title # <title>The Dormouse's story</title> print soup.head # <head><title>The Dormouse's story</title></head> print soup.a # <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a> print soup.p # <p class="title" name="dromouse"><b>The Dormouse's story</b></p> print type(soup.p) # <class 'bs4.element.Tag'>
私たちは、これらのラベルを取得しやすいスープ名札コンテンツを使用することができ、これらの種類のオブジェクトはbs4.element.Tagです。ラベルの要件を満たすために、その中にすべてのものを初めて目であること、しかし、注意してください。あなたはすべてのラベルを照会したい場合、それは後で紹介します。
タグの場合は、名前とattrsにある二つの重要な属性を持っています。次のようにサンプル・コードは次のとおりです。
print soup.name
# [document] #soup 对象本身比较特殊,它的 name 即为 [document]
print soup.head.name
# head #对于其他内部标签,输出的值便为标签本身的名称
print soup.p.attrs # {'class': ['title'], 'name': 'dromouse'} # 在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。 print soup.p['class'] # soup.p.get('class') # ['title'] #还可以利用get方法,传入属性的名称,二者是等价的 soup.p['class'] = "newClass" print soup.p # 可以对这些属性和内容等等进行修改 # <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
2. NavigableString:
取得した場合、ラベルには、コンテンツのラベルを取得したいです。だから、できるtag.string
ラベルテキストを取得します。次のようにサンプル・コードは次のとおりです。
print soup.p.string
# The Dormouse's story
print type(soup.p.string)
# <class 'bs4.element.NavigableString'>thon
3. BeautifulSoup:
BeautifulSoupオブジェクト文書の内容全体を表している。ほとんどの時間、あなたはドキュメントツリーを道のほとんどをサポートしているタグオブジェクトとして扱いと説明したドキュメントツリーを検索することができます。
オブジェクトが本当にBeautifulSoup HTMLやXMLではありませんのでBeautifulSoupオブジェクトは、「[ドキュメント]」特別な属性の値が含まれているので、タグ、それは名前がありませんし、属性プロパティーようにします。しかし、時にはそれが.nameのプロパティビューだが、非常に便利です.nameの
soup.name
# '[document]'
4.コメント:
タグ、NavigableString、BeautifulSoup HTMLやXMLのほぼすべてのコンテンツをカバーしますが、いくつかの特別なオブジェクトが存在しているが、文書のコメントセクションの内容を心配するのは簡単です:
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
type(comment)
# <class 'bs4.element.Comment'>
コメントオブジェクトは、NavigableStringオブジェクトの特殊なタイプです。
comment
# 'Hey, buddy. Want to buy a used parser'
ドキュメントツリーのトラバース:
子ども和1.内容:
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,'lxml')
head_tag = soup.head
# 返回所有子节点的列表 print(head_tag.contents) # 返回所有子节点的迭代器 for child in head_tag.children: print(child)
stripped_strings和2.文字列
タグは、複数のストリングを含む場合、[2]、周期.stringsに使用されてもよい得ます。
for string in soup.strings:
print(repr(string))
# u"The Dormouse's story"
# u'\n\n'
# u"The Dormouse's story" # u'\n\n' # u'Once upon a time there were three little sisters; and their names were\n' # u'Elsie' # u',\n' # u'Lacie' # u' and\n' # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'\n\n' # u'...' # u'\n'
出力文字列は、余分な空白を削除することができ.stripped_stringsを使用し、スペースまたは空白行の多くが含まれる場合があります。
for string in soup.stripped_strings:
print(repr(string))
# u"The Dormouse's story"
# u"The Dormouse's story"
# u'Once upon a time there were three little sisters; and their names were' # u'Elsie' # u',' # u'Lacie' # u'and' # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'...'
検索ドキュメントツリー:
1. findメソッドとfind_all:
ドキュメントツリーを検索し、それは一般的に二つ以上の方法、1使用されているfind
、ものをfind_all
。find
第一の方法は、復帰直後に、一つだけの要素を返す条件を満たすようにラベルを見つけることです。find_all
次に、本方法は、すべての条件がラベルに選択されている満足バック返すことです。これらの2つの方法を使用して、最も一般的な使用法は出ているname
とattr
のパラメータは見つけるためにラベルの要件を満たすために。
soup.find_all("a",attrs={"id":"link2"})
または直接キーワード引数として属性名を渡されます。
soup.find_all("a",id='link2')
2.選択方法:
上記の方法を使用して簡単に要素を識別することができます。しかし、時にはの使用css
セレクタをより簡単に行うことができます。使用css
セレクタ構文を、あなたが使用する必要があるselect
方法を。以下のいくつかの共通しているcss
セレクター方法:
(1)タグ名で検索:
print(soup.select('a'))
(2)クラス名で検索:
クラス名で、それはクラスの前に追加する必要があります.
。例えば、見つけるためにclass=sister
ラベルを。次のようにサンプル・コードは次のとおりです。
print(soup.select('.sister'))
(3)idで検索:
#ID名の前にプラス記号でなければなりませんidで検索。次のようにサンプル・コードは次のとおりです。
print(soup.select("#link1"))
(4)の組み合わせを見つけるのは:
それは組み合わせの原則へのファイル書き込みクラス、ラベル名とクラス名、ID名を検索するために結合されている場合など、コンテンツリンク1に等しいidは、2をスペースで分離する必要がp個のタグを見つけると、同じです。
print(soup.select("p #link1"))
直接の子タグを見つけることは、>のセパレータを使用します。
print(soup.select("head > title"))
(5)財産で検索:
プロパティは、要素を追加したことができます検索、属性は、そうでない場合はそれらが一致することはできません、labelプロパティに注意を払う、括弧で囲まする必要があり、同じノードに属しているので、真ん中には、スペースを追加することはできません。次のようにサンプル・コードは次のとおりです。
print(soup.select('a[href="http://example.com/elsie"]'))
(6)コンテンツへのアクセスを
上記の結果は、選択方法であるフォームは、その内容を取得するための装置、及びその後GET_TEXT()メソッドを通過することができ、リスト形式を返します。
soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text() for title in soup.select('title'): print title.get_text()