From 64753365df3bedd60cde505db792abb20841ada4 Mon Sep 17 00:00:00 2001 From: Leonard Richardson Date: Mon, 11 Nov 2019 11:37:55 -0500 Subject: Moved each translation into its own directory. --- doc.html/index.jp.html | 2822 +++++++++++++++++++++++++++++++++++++ doc.html/index.kr.html | 2476 ++++++++++++++++++++++++++++++++ doc.ptbr/source/6.1.jpg | Bin 0 -> 22619 bytes doc.ptbr/source/conf.py | 256 ++++ doc.ptbr/source/index.rst | 3261 +++++++++++++++++++++++++++++++++++++++++++ doc.zh/source/6.1.jpg | Bin 0 -> 22619 bytes doc.zh/source/index.rst | 2739 ++++++++++++++++++++++++++++++++++++ doc.zh/source/index.zh.html | 2398 ------------------------------- doc/source/README | 23 + doc/source/index.ptbr.rst | 3261 ------------------------------------------- doc/source/index.rst | 21 + 11 files changed, 11598 insertions(+), 5659 deletions(-) create mode 100644 doc.html/index.jp.html create mode 100644 doc.html/index.kr.html create mode 100644 doc.ptbr/source/6.1.jpg create mode 100644 doc.ptbr/source/conf.py create mode 100644 doc.ptbr/source/index.rst create mode 100644 doc.zh/source/6.1.jpg create mode 100644 doc.zh/source/index.rst delete mode 100644 doc.zh/source/index.zh.html create mode 100644 doc/source/README delete mode 100644 doc/source/index.ptbr.rst diff --git a/doc.html/index.jp.html b/doc.html/index.jp.html new file mode 100644 index 0000000..7f5d8e6 --- /dev/null +++ b/doc.html/index.jp.html @@ -0,0 +1,2822 @@ + + + + + + + + kondou.com - Beautiful Soup 4.2.0 Doc. 日本語訳 (2013-11-19最終更新) + + + + + + + + + + + + + +
+
+
+
+ +
+

Beautiful Soup

+"The Fish-Footman began by producing from under his arm a great letter, nearly as large as himself." +

Beautiful Soup はHTMLやXMLファイルからデータを取得するPythonのライブラリです。あなたの好きなパーサー(構文解析器)を使って、パースツリー(構文木)の探索、検索、修正を行います。 +これはプログラマーの作業時間を大幅に短縮してくれます。

+
+

(訳注)石鹸は食べられない

+

この文書は Beautiful Soup 4.2.0 Documentation の日本語訳です。”Beautiful Soup”を”ビューティフルソープ”と読んでしまう英語が苦手でちょっぴりHな後輩のために翻訳しました。

+

2013年10月29日からこの文書の翻訳をはじめました。11月1日現在まだ全てを訳し終えていませんが、スクレイピングに使う主な部分はとりあえず訳したので、一旦これで公開して、あとは年内を目処にまったりと翻訳をすすめ、あわせて質を高めていこうと思っています。今のところ、パースツリーを修正 以降は、ざっくり訳のためにおかしな表現が多々あることにご注意ください。

+

誤訳やわかりづらいところを見つけたり、なにかご意見があるときには、近藤茂徳()までご連絡ください。こういった翻訳をするのははじめてなので、つっこみ大歓迎です。よろしくお願いします。

+

2013年10月現在、Beautiful Soupについての日本語Webページは、Beautiful Soup 3とBeautiful Soup 4(以下、BS3,BS4)の情報が混在しています。とくに、”Beautiful Soup”で日本語ページを対象にググると、最初に表示される10件中9件がBS3による情報であるために、初心者はそのままBS3を使って混乱しがちです。ご注意ください。

+

混乱しないように初心者が知っておくべきこと

+
    +
  • 2012年5月にBS3の開発が終了し、現在ではBS4の利用が推奨されています
  • +
  • BS3はPython3に対応していません
  • +
  • ただし、BS3のスクリプトのほとんどはimport文を変えるだけでBS4でも動きます
  • +
  • そのため、BS3による情報も問題解決の役に立ちます
  • +
  • 詳しくは Beautiful Soup 3 を読んでください
  • +
  • この文書の クイックスタートfind_all() を読めば、それなりに用は足りると思います
  • +
+
+
+

この文書について

+

この文書は、Beautiful Soup 4 (訳注:以下BS4)の主要機能について、例を挙げて説明します。どのライブラリがよいか、どのように動くか、どのように使うか、どのようにあなたの望むことを達成するか、予想外の動きをしたときは何をすればよいかといったことを示します。

+

この文書で挙げられる例は、Python2.7と3.2のどちらでも同じように動きます。

+

あなたは Beautiful Soup 3 (訳注:以下BS3)の文書 を探しているのかもしれません。もしそうなら、BS3はすでに開発を終えていて、BS4が全てのプロジェクト対して推奨されていることを知っていてください。BS3とBS4の違いを知りたいときは、BS4への移行 を見てください。

+

この文書は、ユーザーにより他の言語にも翻訳されています。

+
    +
  • 이 문서는 한국어 번역도 가능합니다.(외부 링크)
  • +
+
+
+

助けてほしいときは

+

Beautiful Soup について疑問が生じたり、問題に直面したときは、 ディスカッショングループにメールしてください。 もし問題がHTMLのパースのことであれば、そのHTMLについて diagnose() 関数の返す内容 を必ず書くようにしてください。

+
+
+
+

クイックスタート

+

以下のHTMLドキュメントは、このあと何回も例として用いられます。 ふしぎの国のアリス からの引用です。:

+
html_doc = """
+<html><head><title>The Dormouse's story</title></head>
+<body>
+<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>
+"""
+
+
+

この”three sisters”ドキュメントを Beautiful Soup にかけると、 Beautiful Soup オブジェクトが得られます。これは入れ子データ構造でドキュメントを表現します。:

+
from bs4 import BeautifulSoup
+soup = BeautifulSoup(html_doc)
+
+print(soup.prettify())
+# <html>
+#  <head>
+#   <title>
+#    The Dormouse's story
+#   </title>
+#  </head>
+#  <body>
+#   <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 class="sister" href="http://example.com/elsie" id="link1">
+#     Elsie
+#    </a>
+#    ,
+#    <a class="sister" href="http://example.com/lacie" id="link2">
+#     Lacie
+#    </a>
+#    and
+#    <a class="sister" href="http://example.com/tillie" id="link2">
+#     Tillie
+#    </a>
+#    ; and they lived at the bottom of a well.
+#   </p>
+#   <p class="story">
+#    ...
+#   </p>
+#  </body>
+# </html>
+
+
+

以下は、データ構造を探索するいくつかの方法です。:

+
soup.title
+# <title>The Dormouse's story</title>
+
+soup.title.name
+# u'title'
+
+soup.title.string
+# u'The Dormouse's story'
+
+soup.title.parent.name
+# u'head'
+
+soup.p
+# <p class="title"><b>The Dormouse's story</b></p>
+
+soup.p['class']
+# u'title'
+
+soup.a
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+soup.find_all('a')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.find(id="link3")
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+
+

よくある処理として、ページの<a>タグ内にあるURLを全て抽出するというものがあります。:

+
for link in soup.find_all('a'):
+    print(link.get('href'))
+# http://example.com/elsie
+# http://example.com/lacie
+# http://example.com/tillie
+
+
+

また、ページからタグを除去して全テキストを抽出するという処理もあります。:

+
print(soup.get_text())
+# The Dormouse's story
+#
+# The Dormouse's story
+#
+# Once upon a time there were three little sisters; and their names were
+# Elsie,
+# Lacie and
+# Tillie;
+# and they lived at the bottom of a well.
+#
+# ...
+
+
+

必要な情報は得られましたか?つづきをどうぞ。

+
+
+

インストール

+

DebianかUbuntuの最近のバージョンを使っていれば、Beautiful Soupはシステムのパッケージマネージャでインストールできます。:

+

$ apt-get install python-bs4

+

Beautiful Soup 4 は PyPiを通して公開されています。そのため、もしシステムパッケージで Beautiful Soup をインストールできないときは、easy_installpip でインストールできます。

+

$ easy_install beautifulsoup4

+

$ pip install beautifulsoup4

+

( BeautifulSoup パッケージはおそらくあなたが探しているものでは ありません 。これは、一つ前のメジャーリリース Beautiful Soup 3 です。多くのソフトウェアがBS3を使っていて、今でもBS3は利用できます。しかし、新しくコードを書く場合は、 beautifulsoup4 をインストールすべきです。)

+

もし、 easy_installpip をインストールしてないときは、download the Beautiful Soup 4 source tarball でソースをダウンロードし setup.py を用いてインストールできます。

+

$ python setup.py install

+

もしどの方法も失敗するのなら、あなたのアプリケーションにライブラリをそのままパッケージングするという手もあります。Beautiful Soupのライセンスはそれを認めています。.tar.gz形式でダウンロードし、アプリケーションのソースコード内に bs4 ディレクトリをコピーしてください。そうすれば、Beautiful Soupをインストールすることなしに使うことができます。

+

私は、Python 2.7とPython 3.2でBeautiful Soupを開発しましたが、他の最近のバージョンでも動くはずです。

+
+

インストール後の問題

+

Beautiful SoupはPython 2のコードとしてパッケージされています。 +Beautiful SoupをPython 3環境で使おうとしてインストールすると、それは自動的にPython 3のコードとして変換されます。 +もし、Beautiful Soupパッケージをインストールしないと、コードは変換されません。 +Windowsでは、間違ったバージョンが入っていると、それが報告されます。

+

ImportError “No module named HTMLParser” というエラーが表示されたら、それはPython 3環境でPython 2で書かれたコードを実行しようとしたためです。

+

ImportError “No module named html.parser” というエラーが表示されたら、それはPython 2環境でPython 3ので書かれたコードを実行しようとしたためです。

+

どちらの場合もとるべき対応は、Beautiful Soupを(tarballを解凍したときディレクトリを含め) +完全にアンインストールして、再インストールをすることです。

+

ROOT_TAG_NAME = u'[document]' 行で SyntaxError “Invalid syntax” のエラーが表示されたら、 +Python 2で書かれたBeautiful SoupのコードをPython 3に変換しなければいけません。

+

そのためには、次のようにパッケージをインストールするか、:

+

$ python3 setup.py install

+

もしくは、手動で 2to3 変換スクリプトを bs4 ディレクトリで実行すればできます。:

+

$ 2to3-3.2 -w bs4

+
+
+

パーサーのインストール

+

Beautiful SoupはPythonの標準ライブラリに入っているHTMLパーサーをサポートすると同時に、多くのサードパーティーのPythonパーサーもサポートしています。一つには、 lxml parser. があります。環境に依りますが、以下のコマンドのどれかでlxmlをインストールできるでしょう。:

+

$ apt-get install python-lxml

+

$ easy_install lxml

+

$ pip install lxml

+

別の選択肢として、Python純正の html5lib parser が挙げられます。これは HTMLをwebブラウザがするようにパースします。これも環境に依りますが、以下のコマンドのどれかでhtml5libをインストールできるでしょう。:

+

$ apt-get install python-html5lib

+

$ easy_install html5lib

+

$ pip install html5lib

+

以下の表は、各パーサーのライブラリの強みと弱みをまとめてあります。

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
パーサー使用例強み弱み
Python’s html.parserBeautifulSoup(markup, "html.parser")
    +
  • 標準ライブラリ
  • +
  • まずまずのスピード
  • +
  • Python2.7.3/3.2.2以降に対応
  • +
+
    +
  • Python2.7.3/3.2.2未満は非対応
  • +
+
lxml’s HTML parserBeautifulSoup(markup, "lxml")
    +
  • 爆速
  • +
  • 対応(?)
  • +
+
    +
  • 外部Cライブラリに依存
  • +
+
lxml’s XML parserBeautifulSoup(markup, ["lxml", "xml"]) +BeautifulSoup(markup, "xml")
    +
  • 爆速
  • +
  • 唯一の対応XMLパーサー
  • +
+
    +
  • 外部Cライブラリに依存
  • +
+
html5libBeautifulSoup(markup, "html5lib")
    +
  • 対応度高
  • +
  • WEBブラウザと同じようにパース
  • +
  • 正しいHTML5を生成
  • +
+
    +
  • とても遅い
  • +
  • 外部Pythonライブラリに依存
  • +
+
+

できれば、速度のためにlxmlをインストールして使うことをお薦めします。 +とくに、あなたがPython2.7.3のPython2系か、Python3.2.2より前のPython3系を使っているばあいは、lxmlかhtml5libをインストールすることは とても大事です 。 +なぜなら、Pythonにはじめから組み込まれているHTMLパーサーは、古いバージョンのPythonではそこまで良く動かないからです。

+

構文が不正確なドキュメントのときは、パーサーが違うと生成されるパースツリーが異なってくることに注意してください。 +詳しくは、 パーサーの違い を参照のこと。

+
+
+
+

スープの作成

+

ドキュメントをパース(構文解析)するには、 +そのドキュメントを Beautiful Soup コンストラクタに渡します。 +文字列でも開いたファイルハンドルでも渡せます。:

+
from bs4 import BeautifulSoup
+
+soup = BeautifulSoup(open("index.html"))
+
+soup = BeautifulSoup("<html>data</html>")
+
+
+

最初に、ドキュメントはUnicodeに変換され、HTMLエンティティはUnicode文字列に変換されます。:

+
BeautifulSoup("Sacr&eacute; bleu!")
+<html><head></head><body>Sacré bleu!</body></html>
+
+

Beautiful Soupは、ドキュメントをもっとも適したパーサー(構文解析器)を使ってパースします。 +XMLパーサーを使うように指定しなければ、HTMLパーサーが用いられます。( XMLのパース を参照)

+
+
+

4種類のオブジェクト

+

Beautiful Soup は複雑なHTMLドキュメントを、Pythonオブジェクトの複雑なツリー構造に変換します。 +しかし、あなたは Tag, NavigableString, BeautifulSoup, Comment +の 4種類のオブジェクト だけを扱えばよいです。

+
+

Tag obj.

+

Tag オブジェクトは、元のドキュメント内のXMLやHTMLのタグに対応しています。:

+
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
+tag = soup.b
+type(tag)
+# <class 'bs4.element.Tag'>
+
+
+

Tag オブジェクトは、多くの属性とメソッドを持っています。それらのほとんどは、 パースツリーを探索パースツリーを検索 で説明します。この節では Tag オブジェクトの重要な機能である、名前と属性について説明します。

+
+

名前

+

タグはそれぞれ名前を持っていますが、 .name でアクセスできます。:

+
tag.name
+# u'b'
+
+
+

タグの名前を変えると、その変更はBeautiful Soupが生成する全てのマークアップに反映されます。:

+
tag.name = "blockquote"
+tag
+# <blockquote class="boldest">Extremely bold</blockquote>
+
+
+
+
+

属性

+

タグは多くの属性を持ちます。 +<b class=”boldest”>は、”boldest”という値の’class’属性を持ちます。 +Tag オブジェクトを辞書のように扱うことで、そのタグの属性にアクセスできます。:

+
tag['class']
+# u'boldest'
+
+
+

.attrs で辞書に直接アクセスできます。:

+
tag.attrs
+# {u'class': u'boldest'}
+
+
+

繰り返しになりますが、辞書のように Tag オブジェクトを扱うことにより、タグの属性に対して追加, 削除, 修正も行うことができます。:

+
tag['class'] = 'verybold'
+tag['id'] = 1
+tag
+# <blockquote class="verybold" id="1">Extremely bold</blockquote>
+
+del tag['class']
+del tag['id']
+tag
+# <blockquote>Extremely bold</blockquote>
+
+tag['class']
+# KeyError: 'class'
+print(tag.get('class'))
+# None
+
+
+
+

値が複数のとき

+

HTML4は、値を複数もてる2,3の属性を定義しています。 +HTML5で、それらはなくなりましたが、別の同様の属性が定義されました。 +もっとも一般的な値を複数もつ属性は class です。(たとえば、HTMLタグは複数のCSSクラスを持つことができます) +また他の複数の値を持つ属性としては、 rel, rev, accept-charset, headers, accesskey があります。 +Beautiful Soupは、これらの属性がもつ複数の値をリストとして示します。:

+
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
+css_soup.p['class']
+# ["body", "strikeout"]
+
+css_soup = BeautifulSoup('<p class="body"></p>')
+css_soup.p['class']
+# ["body"]
+
+
+

ある属性が複数の値をもっているようでも、HTML標準の定義から外れている場合、Beautiful Soupはその属性をひとまとまりの値として扱います。:

+
id_soup = BeautifulSoup('<p id="my id"></p>')
+id_soup.p['id']
+# 'my id'
+
+
+

タグを文字列に変換したときは、これらの属性の複数の値は一つにまとめられます。:

+
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>')
+rel_soup.a['rel']
+# ['index']
+rel_soup.a['rel'] = ['index', 'contents']
+print(rel_soup.p)
+# <p>Back to the <a rel="index contents">homepage</a></p>
+
+
+

ドキュメントをXMLとしてパースすると、値を複数もつ属性はなくなります。:

+
xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml')
+xml_soup.p['class']
+# u'body strikeout'
+
+
+
+
+
+ +
+

BeautifulSoup obj.

+

Beautiful Soup オブジェクトは、それ自身で元のドキュメント全体を表しています。 +たいていの場合、Tag obj. を扱うことで、用は足りるでしょう。 +これは、Tag obj.パースツリーを探索パースツリーを検索. で述べられているメソッドの多くをサポートしているということです。

+

BeautifulSoup オブジェクトは、実際のHTMLやXMLタグに対応していないので、名前や属性を持たない。 +しかし、 .name をみるような便利なものはいくつかある。そして、それらは特別な .name “[document]”を得られる(?訳がおかしい。けど次回まわし?):

+
soup.name
+# u'[document]'
+
+
+
+
+

Comments obj. 他

+

Tag, 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'>
+
+
+

Comment オブジェクトは、 NavigableString オブジェクトの特別なタイプです。:

+
comment
+# u'Hey, buddy. Want to buy a used parser'
+
+
+

コメントはHTMLの中にあらわれますが、 Comment は特別な書式で表示されます。:

+
print(soup.b.prettify())
+# <b>
+#  <!--Hey, buddy. Want to buy a used parser?-->
+# </b>
+
+
+

Beautiful Soupは、XMLドキュメントのなかの他の全ての要素をクラス定義しています。 +CData, ProcessingInstruction, Declaration, Doctype. +Comment クラスのように、これらは文字に何かを加えた NavigableString のサブクラスです。 +ここでは、コメントをCDDATAブロックに置換した例を示します。:

+
from bs4 import CData
+cdata = CData("A CDATA block")
+comment.replace_with(cdata)
+
+print(soup.b.prettify())
+# <b>
+#  <![CDATA[A CDATA block]]>
+# </b>
+
+
+
+
+
+

パースツリーを探索

+

ここで再び “Three sisters” のHTMLドキュメントです。:

+
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)
+
+
+

ドキュメントのある部分から他の部分へどのように移動するかを示すために、このドキュメントを例に使っていきます。

+
+

子要素へ下移動

+

タグはその間に(ドキュメント本文のテキスト)文字列や他のタグを挟んでいます。これらの要素は、 タグの 子要素 です。Beautiful Soupは、タグの子要素を探索し扱うための多くの属性を提供します。

+

Beautiful Soupの文字列は、これらの属性をサポートしません。なぜなら、文字列は子要素をもたないからです。

+
+

タグ名で探索

+

パースツリーを探索する一番簡単な方法は、あなたが取得したいタグの名前を使うことです。 +もし、<head> タグを取得したければ、 soup.head と入力すればよいです。:

+
soup.head
+# <head><title>The Dormouse's story</title></head>
+
+soup.title
+# <title>The Dormouse's story</title>
+
+
+

また、パースツリーのある部分から出発して、何度もズームインを繰り返す方法もあります。 +このコードは、<body>タグ以下の最初の<b>タグを取得します。:

+
soup.body.b
+# <b>The Dormouse's story</b>
+
+
+

属性としてタグ名を使うと、その名前のタグのうち 最初 にあるものを取得できます。:

+
soup.a
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+
+

全ての <a>タグを取得したいときや、ある名前のタグのうち2番目以降のものをしたいときは、 パースツリーを検索 で述べられている find_all() のようなメソッドを使う必要があります。:

+
soup.find_all('a')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+
+
+

.contents / .children

+

タグの子要素は、 .contents で呼び出すと、リストで取得できます。:

+
head_tag = soup.head
+head_tag
+# <head><title>The Dormouse's story</title></head>
+
+head_tag.contents
+[<title>The Dormouse's story</title>]
+
+title_tag = head_tag.contents[0]
+title_tag
+# <title>The Dormouse's story</title>
+title_tag.contents
+# [u'The Dormouse's story']
+
+

Beautiful Soup オブジェクトは、それ自身が子要素を持ちます。この場合、<html>タグが Beautiful Soup オブジェクトの子要素になります。:

+
len(soup.contents)
+# 1
+soup.contents[0].name
+# u'html'
+
+
+

文字列は .contents を持ちません。なぜなら、文字列は何も挟まないからです。:

+
text = title_tag.contents[0]
+text.contents
+# AttributeError: 'NavigableString' object has no attribute 'contents'
+
+
+

タグの子要素を、リストの代わりに、 .children ジェネレーターを用いてイテレーターで扱うこともできます。:

+
for child in title_tag.children:
+    print(child)
+# The Dormouse's story
+
+
+
+
+

.descendants

+

.contents.children 属性は、あるタグの 直下の 子要素のみを表します。 +例えば、<head>タグは、ただ一つの直下の子要素である<title>タグを持ちます。:

+
head_tag.contents
+# [<title>The Dormouse's story</title>]
+
+
+

しかし、この<title>タグ自身も、子要素に”The Dormouse’s story”文字列を持ちます。 +この文字列もまた、<head>タグの子要素であるという意味になります。 +そこで、 .descendants (子孫) 属性を用いると、 あるタグの 全ての 子要素を再帰的に取り出すことができます。 +再帰的というのは、直下の子要素、そのまた子要素、そしてさらにといったふうに繰り返してということです。

+
for child in head_tag.descendants:
+    print(child)
+# <title>The Dormouse's story</title>
+# The Dormouse's story
+
+
+

このドキュメントの<head>タグはただ1つの子要素しか持ちませんが、 +<title>タグと<title>タグの子要素という2つの子孫要素を持ちます。 +また、このドキュメントの BeautifulSoup オブジェクトには、 +直下の子要素は<html>タグ1つしかありませんが、子孫要素はたくさんあります。:

+
len(list(soup.children))
+# 1
+len(list(soup.descendants))
+# 25
+
+
+
+
+

.string

+

ある Tag オブジェクトが1つだけ子要素をもっていて、その子要素が NavigableString オブジェクトならば、 .string 属性で利用できます。:

+
title_tag.string
+# u'The Dormouse's story'
+
+
+

ある Tag オブジェクトのただ1つの子要素が、別の Tag オブジェクトであって .string 属性を持つならば、元の Tag オブジェクトも同じ .string 属性を持つと考えられます。:

+
head_tag.contents
+# [<title>The Dormouse's story</title>]
+
+head_tag.string
+# u'The Dormouse's story'
+
+
+

ある tag オブジェクトが複数の子要素を持ち、 .string 属性がどの子要素を参照しているかわからないとき、 .string 属性は None と定義されます。:

+
print(soup.html.string)
+# None
+
+
+
+
+

.strings / .stripped_strings

+

あるタグの中にあるドキュメント本文が要素が複数であっても、それらの文字列をみることができます。 +その場合は、 .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'...'
+
+
+

ここでは、文字列中に入る空白はそのままで、文字列の最初や最後に付く空白は削除されます。

+
+
+
+

親要素へ上移動

+

“家族ツリー”に例えると、全てのタグや文字列はそれぞれが一つの親要素を持ちます。

+
+

.parent

+

.parent 属性で親要素にアクセスできます。 +たとえば、”three sisters”ドキュメントでは、<head>タグは<title>タグの親要素です。:

+
title_tag = soup.title
+title_tag
+# <title>The Dormouse's story</title>
+title_tag.parent
+# <head><title>The Dormouse's story</title></head>
+
+
+

タイトル文字列はそれ自身が親要素を持ち、<title>タグはタイトル文字列を子要素に持ちます。:

+
title_tag.string.parent
+# <title>The Dormouse's story</title>
+
+
+

<html>タグの様なトップレベルのタグは、 BeautifulSoup オブジェクトそれ自身になります。:

+
html_tag = soup.html
+type(html_tag.parent)
+# <class 'bs4.BeautifulSoup'>
+
+
+

そして、BeautifulSoup オブジェクトの .parent 属性は、Noneになります。:

+
print(soup.parent)
+# None
+
+
+
+
+

.parents

+

あるタグに対する祖先要素全てを .parents で取得することができます。 +以下は、HTMLドキュメントの深いところにある<a>タグからスタートして、最上層まで辿っています。:

+
link = soup.a
+link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+for parent in link.parents:
+    if parent is None:
+        print(parent)
+    else:
+        print(parent.name)
+# p
+# body
+# html
+# [document]
+# None
+
+
+
+
+
+

兄弟要素へ横移動

+

以下のようなシンプルなHTMLドキュメントを考えてみましょう。:

+
sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
+print(sibling_soup.prettify())
+# <html>
+#  <body>
+#   <a>
+#    <b>
+#     text1
+#    </b>
+#    <c>
+#     text2
+#    </c>
+#   </a>
+#  </body>
+# </html>
+
+
+

<b>タグは<c>タグと同じレベルにあります。つまり、2つはともに同じタグの直下の子要素ということです。 +こういった関係にあるタグを siblings (兄弟)といいます。 +HTMLドキュメントをきれいに出力(?)したとき、siblingsは同じインデントレベルになります。 +こういったタグの関係をコードで利用することができます。

+
+

.next_sibling / .previous_sibling

+

.next_sibling.previous_sibling を用いて、パースツリーの同じレベルの要素間を辿ることができます。:

+
sibling_soup.b.next_sibling
+# <c>text2</c>
+
+sibling_soup.c.previous_sibling
+# <b>text1</b>
+
+
+

この<b>タグは .next_sibling は持ちますが、 .previous_sibling は持ちません。 +なぜなら、<b>タグの前にはパースツリーで同レベルの要素がないからです。 +同様に、<c>タグは .previous_sibling を持ちますが、.next_sibling は持ちません。:

+
print(sibling_soup.b.previous_sibling)
+# None
+print(sibling_soup.c.next_sibling)
+# None
+
+
+

“text1”と”text”は兄弟ではありません。なぜなら、2つは同じ親をもたないからです。:

+
sibling_soup.b.string
+# u'text1'
+
+print(sibling_soup.b.string.next_sibling)
+# None
+
+
+

実際のHTMLドキュメントをパースすると、 .next_sibling.previous_sibling は前後に空白を持ちます。 +“three sisters”ドキュメントで見てみましょう。:

+
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
+<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
+<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
+
+

すなおに考えれば、最初の<a>タグの .next_sibling は2番目の<a>タグとなるはずですが、実際は違います。 +それは、最初の<a>タグと2番目を分ける”コンマと改行コード”という文字列になります。:

+
link = soup.a
+link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+link.next_sibling
+# u',\n'
+
+
+

2番目の<a>タグは、そのコンマと改行コードの .next_sibling になります。:

+
link.next_sibling.next_sibling
+# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
+
+
+
+
+

.next_siblings / .previous_siblings

+

複数の兄弟要素を .next_siblings.previous_siblings をイテレーターとして使って、まとめて扱えます。:

+
for sibling in soup.a.next_siblings:
+    print(repr(sibling))
+# u',\n'
+# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
+# u' and\n'
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+# u'; and they lived at the bottom of a well.'
+# None
+
+for sibling in soup.find(id="link3").previous_siblings:
+    print(repr(sibling))
+# ' and\n'
+# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
+# u',\n'
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+# u'Once upon a time there were three little sisters; and their names were\n'
+# None
+
+
+
+
+
+

前後の要素へ移動

+

“three sisters”ドキュメントのはじめの部分を見てみましょう。:

+
<html><head><title>The Dormouse's story</title></head>
+<p class="title"><b>The Dormouse's story</b></p>
+
+

HTMLパーサーは、この文字列を読み込み、イベントの連なりとして理解します。”open an <html> tag”, “open a <head> tag”, “open a <title> tag”, “add a string”, “close the <title> tag”, “open a <p>”... といったかんじです。Beautiful Soupはこのイベントの連なりを、さらに再構成して扱います。

+
+

.next_element / .previous_element

+

文字列やHTMLタグの .next_element 属性は、それの直後の要素を指し示します。 +.next_string と同じようですが、決定的に違います。

+

“three sisters”ドキュメントの最後の<a>タグについて考えてみましょう。 +それの .next_string はその<a>タグによって分割された文の後ろの部分の文字列です。(?):

+
last_a_tag = soup.find("a", id="link3")
+last_a_tag
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+last_a_tag.next_sibling
+# '; and they lived at the bottom of a well.'
+
+
+

一方、 .next_element は、<a>タグのすぐ後ろの要素である”Tillie”という単語を指し示します。文の残りの部分ではありません。:

+
last_a_tag.next_element
+# u'Tillie'
+
+
+

これは元の文章で”Tillie”という単語がセミコロンの前に現れるからです。 +パーサーは<a>タグに出会い、次に”Tillie”という単語、そして</a>という閉じるタグがきます。 +そのあとは、セミコロンがあって、文の残りの部分です。 +セミコロンは<a>タグと同じレベルにありますが、”Tillie”という単語が最初に出会います。

+

.previous_element 属性は、 .next_element とは逆です。 +その要素の一つ前の要素を指し示します。:

+
last_a_tag.previous_element
+# u' and\n'
+last_a_tag.previous_element.next_element
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+
+
+
+

.next_elements / .previous_elements

+

パースされたドキュメントの要素を、前後方向に取得していくイテレーターを使うこともできます。:

+
for element in last_a_tag.next_elements:
+    print(repr(element))
+# u'Tillie'
+# u';\nand they lived at the bottom of a well.'
+# u'\n\n'
+# <p class="story">...</p>
+# u'...'
+# u'\n'
+# None
+
+
+
+
+
+
+

パースツリーを検索

+

Beautiful Soupはパースパースツリーを検索する多くのメソッドを定義しています。 +しかし、それらはどれもとても似通っています。 +この章では、find()find_all() という2つの人気のメソッドの説明に、多くのスペースを費やします。 +それ以外のメソッドは、ほとんど同じ引数を持つので、簡単な説明にとどめることにします。

+

ここでは再び、”three sisters”ドキュメントを例に使っていきます。:

+
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)
+
+
+

find_all() のようなフィルターを通すことにより、 +興味のあるドキュメントのある一部分にズームすることができます。

+
+

フィルターの種類

+

find_all() 等のメソッドの詳細を説明するまえに、これらのメソッドに渡すフィルターの例を示します。 +検索APIの使い方をマスターする上で、フィルターは何度もでてきます。 +これにより、タグ名, タグの属性, ドキュメントの文字列やそれを組み合わせた条件を指定して、フィルターをかけます

+
+

文字列

+

もっともシンプルなフィルターは文字列です。 +検索メソッドに文字列を渡すと、Beautiful Soupは厳格に文字列を一致させます。 +以下のコードは、ドキュメント内の<b>タグを全て見つけます。:

+
soup.find_all('b')
+# [<b>The Dormouse's story</b>]
+
+
+

バイト文字列を渡すと、Beautiful SoupはそれをUTF-8にエンコードされた文字列として扱います。 +これを避けるには、代わりにUnicode文字列を渡します。

+
+
+

正規表現

+

正規表現オブジェクトを渡すと、Beautiful Soupはそれの match() メソッドを用いて、その正規表現に一致するものをマッチさせます。 +以下のコードは、全ての”b”ではじまるつづりの名前のタグを見つけます。 +“three sisters”ドキュメントでは、<body>タグと<b>タグにマッチします。:

+
import re
+for tag in soup.find_all(re.compile("^b")):
+    print(tag.name)
+# body
+# b
+
+
+

以下のコードでは、タグ名に”t”のつづりを含むもの全てを見つけます。:

+
for tag in soup.find_all(re.compile("t")):
+    print(tag.name)
+# html
+# title
+
+
+
+
+

リスト

+

フィルターにリストで引数をわたすと、Beautiful Soupはそのリストの内のいずれかにマッチした要素を返します。 +以下のコードは、全ての<a>タグと<b>タグを見つけます。:

+
soup.find_all(["a", "b"])
+# [<b>The Dormouse's story</b>,
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+
+
+

True値

+

True値 は全ての要素にマッチします。 +以下のコードは、ドキュメント内の 全て のタグをみつけます。 +ただし、ドキュメント本文のテキスト文字列はマッチされません。:

+
for tag in soup.find_all(True):
+    print(tag.name)
+# html
+# head
+# title
+# body
+# p
+# b
+# p
+# a
+# a
+# a
+# p
+
+
+
+
+

関数

+

以上のフィルターで機能が足りないときは、自分で引数に要素をとる関数を定義することもできます。 +その関数は、引数がマッチしたときは True を、そうでないときは False を返します。

+

以下の関数では、HTMLタグが “class” 属性を持ち、”id”属性を持たない場合に True を返します。:

+
def has_class_but_no_id(tag):
+    return tag.has_attr('class') and not tag.has_attr('id')
+
+
+

この関数を find_all() に渡すと、”three sisters”ドキュメントから全ての<p>タグを取得できます。:

+
soup.find_all(has_class_but_no_id)
+# [<p class="title"><b>The Dormouse's story</b></p>,
+#  <p class="story">Once upon a time there were...</p>,
+#  <p class="story">...</p>]
+
+
+

この関数は<p>タグだけを抽出します。 +<a>タグは”class”と”id”の両方の属性を定義しているので抽出できません。 +<html>や<title>のようなタグは、”class”を定義してないので、同様に抽出できません。

+

以下の関数は、HTMLタグがstringオブジェクトに囲まれているときは、 True を返します。(?):

+
from bs4 import NavigableString
+def surrounded_by_strings(tag):
+    return (isinstance(tag.next_element, NavigableString)
+            and isinstance(tag.previous_element, NavigableString))
+
+for tag in soup.find_all(surrounded_by_strings):
+    print tag.name
+# p
+# a
+# a
+# a
+# p
+
+
+

これで検索メソッドの詳細をみていくことの準備ができました。

+
+
+
+

find_all()

+

使い方: find_all(name, attrs, recursive, text, limit, **kwargs)

+

find_all() メソッドは、Tag オブジェクトが持つ子孫要素のうち、引数に一致する 全ての 要素を見つけます。 +フィルターの種類 でいくつかの例を挙げましたが、ここでもう少し説明します。:

+
soup.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+soup.find_all("p", "title")
+# [<p class="title"><b>The Dormouse's story</b></p>]
+
+soup.find_all("a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.find_all(id="link2")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+import re
+soup.find(text=re.compile("sisters"))
+# u'Once upon a time there were three little sisters; and their names were\n'
+
+
+

これらの使い方は、すでに説明してるものもあれば、初出のものもあります。 +textid に値を渡すのはどういう意味でしょうか? +なぜ、find_all("p", "title") は、CSSの”title”タグをもつ<p>タグを発見したのでしょうか? +find_all() の引数をみていきましょう。

+
+

name引数

+

find_all()name 引数に値を渡すと、タグの名前だけを対象に検索が行われます。 +名前がマッチしないタグと同じように、テキスト文字列は無視されます。

+

以下の例は、もっともシンプルな使い方です。:

+
soup.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+
+

フィルターの種類 で述べたように、 name 引数は文字列, 正規表現, リスト, 関数, True値をとることができます。

+
+
+

キーワード引数

+

どのような理解できない引数でも、タグの属性の一つとして解釈されます。 +キーワード引数 id に値を渡すと、Beautiful Soupはタグの’id’属性に対してフィルタリングを行います。:

+
soup.find_all(id='link2')
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+

キーワード引数 href に値を渡すと、Beautiful SoupはHTMLタグの’href’属性に対してフィルタリングを行います。:

+
soup.find_all(href=re.compile("elsie"))
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+
+

キーワード引数の値もまた、 文字列, 正規表現, リスト, 関数, True値 をとることができます。

+

次のコードは、id 属性に値が入っている全てのタグを見つけます。このとき、値は何でもあっても構いません。:

+
soup.find_all(id=True)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

複数のキーワード引数を一度に渡すことによって、複数の属性についてフィルタリングできます。:

+
soup.find_all(href=re.compile("elsie"), id='link1')
+# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
+
+
+

HTML5の ‘data-*’ 属性など、いくつかの属性についてはキーワード引数として用いることができません。:

+
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
+data_soup.find_all(data-foo="value")
+# SyntaxError: keyword can't be an expression
+
+
+

しかし、これらの属性を辞書にして、キーワード引数 attrs として値を渡せばフィルタリングすることができます。:

+
data_soup.find_all(attrs={"data-foo": "value"})
+# [<div data-foo="value">foo!</div>]
+
+
+
+
+

CSSのクラスで検索

+

HTMLタグが持つCSSのクラスで検索をかけるのはとても便利です。 +しかし”class”はPythonの予約語のため、class をキーワード引数として用いると文法エラーになります。 +そこで、Beautiful Soup 4.1.2からは、 class_ というキーワード引数でCSSのクラスを検索できるようになりました。:

+
soup.find_all("a", class_="sister")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

他のキーワード引数と同様、 class_ には文字列, 正規表現, 関数, True値を渡せます。:

+
soup.find_all(class_=re.compile("itl"))
+# [<p class="title"><b>The Dormouse's story</b></p>]
+
+def has_six_characters(css_class):
+    return css_class is not None and len(css_class) == 6
+
+soup.find_all(class_=has_six_characters)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

Tag オブジェクトの属性の 値が複数のとき を思い出してください。 +それと同様に、あるCSSクラスを検索するときは、複数のCSSクラスに対してマッチさせられます。:

+
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
+css_soup.find_all("p", class_="strikeout")
+# [<p class="body strikeout"></p>]
+
+css_soup.find_all("p", class_="body")
+# [<p class="body strikeout"></p>]
+
+
+

class 属性の値は、文字列としても検索できます。:

+
css_soup.find_all("p", class_="body strikeout")
+# [<p class="body strikeout"></p>]
+
+
+

しかし、文字列の値としての変数を検索することはできません。:

+
css_soup.find_all("p", class_="strikeout body")
+# []
+
+
+

もしあなたが2つ以上のクラスをまっちさせたいなら、CSSセレクトを使ってください。:

+
css_soup.select("p.strikeout.body")
+# [<p class="body strikeout"></p>]
+
+
+

Beautiful Soupの古いバージョンでは、 class_ 引数は使えません。 +そこで、以下に述べる attrs トリックを使うことができます。 +これは”class”をkeyに持つ辞書を attrs 引数に渡して、検索することができます。 +この辞書のvalueには、文字列, 正規表現などが使えます。:

+
soup.find_all("a", attrs={"class": "sister"})
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+
+
+

text引数

+

text 引数で、タグに挟まれている文字列を対象に検索することができます。 +name 引数やキーワード引数のように、 文字列 , 正規表現 , リスト , 関数 , True値 が使えます。 +以下の例をごらんください。:

+
soup.find_all(text="Elsie")
+# [u'Elsie']
+
+soup.find_all(text=["Tillie", "Elsie", "Lacie"])
+# [u'Elsie', u'Lacie', u'Tillie']
+
+soup.find_all(text=re.compile("Dormouse"))
+[u"The Dormouse's story", u"The Dormouse's story"]
+
+def is_the_only_string_within_a_tag(s):
+    """Return True if this string is the only child of its parent tag."""
+    return (s == s.parent.string)
+
+soup.find_all(text=is_the_only_string_within_a_tag)
+# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']
+
+
+

text 引数はテキスト文字列の検索ですが、これにタグの検索を組みわせることもできます。 +Beautiful Soupは、text 引数で指定した文字列を .string にもつタグ全てを見つけます。 +次のコードは、.string に “Elsie”を持つ<a>タグを見つけます。:

+
soup.find_all("a", text="Elsie")
+# [<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>]
+
+
+
+
+

limit引数

+

find_all() メソッドは、指定したフィルターにマッチした全てのタグと文字列を返します。 +これはドキュメントが大きいときは時間がかかります。 +もし、 全ての 結果を必要としなければ、limit 引数で取得する数を指定することができます。

+

“three siters”ドキュメントには3つのリンクがある、しかし以下のコードははじめの2つしか見つけない。:

+
soup.find_all("a", limit=2)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+
+
+

recursive引数

+

mytag.find_all() を実行すると、Beautiful Soupは、 mytag の全ての子孫要素を調べます。 +(子要素、子要素の子要素、そのまた子要素というかんじで、、) +もし、直下の子要素しか調べたくなければ、recursive=False という引数を渡せばよいです。 +以下で違いをみてみましょう。:

+
soup.html.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+soup.html.find_all("title", recursive=False)
+# []
+
+
+

これはドキュメントの一部です。:

+
<html>
+ <head>
+  <title>
+   The Dormouse's story
+  </title>
+ </head>
+...
+
+

このドキュメントにおいて、<title>タグは<html>の下にはあるが、直下 にあるわけではありません。 +Beautiful Soupが<title>タグを見つけることができるのは、<html>タグ以下の全ての子孫要素を探してよいときだけです。 +もし、find_all() の引数に recurive=False という<html>タグの直下のみを検索するという制限がかかっていたら、<title>タグを見つけることはできません。

+

Beautiful Soupは、多くのパースツリーを検索するメソッドを提供しています。 +それら多くは共通する引数を持ちます。 +find_all()name, attrs, text, limit, キーワード引数は、他の多くのメソッドにも対応しています。 +しかし、 recursive 引数は、 find_all(), find() の2つのメソッドしか対応していません。 +find_parents() のようなメソッドに、引数 recursive=False を渡しても意味がありません。

+
+
+

ショートカット

+

find_all() はBeautiful Soupの検索APIの中で、一番使われるものなので、ショートカットがあります。 +Beautiful Soup オブジェクトや Tag オブジェクトを関数のように扱って、 find_all() メソッドを呼び出すことができます。 +以下の2行は等価です。:

+
soup.find_all("a")
+soup("a")
+
+
+

以下の2行もまた等価です。:

+
soup.title.find_all(text=True)
+soup.title(text=True)
+
+
+
+
+
+

find()

+

使い方: find(name, attrs, recursive, text, **kwargs)

+

find_all() メソッドは、検索結果を得るためにHTMLドキュメント全部をスキャンします。 +しかし、1つだけの検索結果が必要なときがあります。 +もし、HTMLドキュメントに<body>タグが1つだけなら、HTMLドキュメント全体をスキャンするのは時間の無駄です。 +その場合は find_all() メソッドに limit=1 という引数を渡さずに、 find() メソッドを使うことができます。 +以下の2行は、ほぼ等価です。:

+
soup.find_all('title', limit=1)
+# [<title>The Dormouse's story</title>]
+
+soup.find('title')
+# <title>The Dormouse's story</title>
+
+
+

ただ1つ違う点は、find_all() は要素1のリストを返し、find() は要素をそのまま返すことです。

+

find_all() が何もみつけられないときは空リストを返します。 +find() が何もみつけられないときは、 None を返します。:

+
print(soup.find("nosuchtag"))
+# None
+
+
+

タグ名で探索 で出てきた soup.head.title で探索する方法を覚えていますか? おkれは、find() についても適用できます。:

+
soup.head.title
+# <title>The Dormouse's story</title>
+
+soup.find("head").find("title")
+# <title>The Dormouse's story</title>
+
+
+
+
+

find_parents() / find_parent()

+

使い方: find_parents(name, attrs, text, limit, **kwargs)

+

使い方: find_parent(name, attrs, text, **kwargs)

+

ここまで find_all()find() について述べてきました。 +Beautiful Soup APIにはパースツリーを検索するためのメソッドが、あと10あります。 +しかし、おそれる必要はありません。 +そのうち5つは、find_all() と基本的に同じです。 +そして、のこりの5つは find() と基本的に同じです。 +違いは、ツリーのどの部分を検索対象にするのかという点のみです。

+

最初に、 find_parents()find_parent() を見てみましょう。 +find_all()find() がタグの子孫を見て、ツリーを下りていったことを思い出してください。 +find_parents()find_parent() は逆です。 +これらはタグや文字列の親をみて、ツリーを’上に’検索していきます。 +以下の”three daughters”ドキュメントの例で、深いレベルにある文字列から検索していく様子を見てください。:

+
a_string = soup.find(text="Lacie")
+a_string
+# u'Lacie'
+
+a_string.find_parents("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+a_string.find_parent("p")
+# <p class="story">Once upon a time there were three little sisters; and their names were
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
+#  and they lived at the bottom of a well.</p>
+
+a_string.find_parents("p", class="title")
+# []
+
+

3つの<a>タグのうちの1つは、検索の起点になる文字列の直接の親要素なので、それが返されました。 +3つの<p>タグのうちの1つは、起点の文字列の直接の親ではありませんが、やはりそれも返されました。 +CSSクラス”title”をもつ<p>タグは、”three daughers”ドキュメント中にはあるのですが、起点の文字列の親要素ではないので、 find_parents() では見つけることができませんでした。

+

find_parent()find_parents() のつながりはわかったでしょうか。 +.parent.parents 属性については、以前に述べてあります。 +そのつながりはとても強いです。 +これらの検索メソッドは実際には .parents で、全ての親要素の連なりをイテレートして扱います。 +そして、要素それぞれについてフィルターにマッチするかどうかをチェックします。

+
+
+

find_next_siblings() / find_next_sibling()

+

使い方: find_next_siblings(name, attrs, text, limit, **kwargs)

+

使い方: find_next_sibling(name, attrs, text, **kwargs)

+

これらのメソッドは、後方にある兄弟要素を扱うのに、 .next_siblings を使います。 +find_next_siblings() メソッドはマッチする兄弟要素を全て返し、 find_next_sibling() は最初の一つを返します。:

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_next_siblings("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+first_story_paragraph = soup.find("p", "story")
+first_story_paragraph.find_next_sibling("p")
+# <p class="story">...</p>
+
+
+
+
+

find_previous_siblings() / find_previous_sibling()

+

使い方: find_previous_siblings(name, attrs, text, limit, **kwargs)

+

使い方: find_previous_sibling(name, attrs, text, **kwargs)

+

これらのメソッドは、HTMLドキュメントの前方にあった兄弟要素を扱うのに .previous_siblings を使います。 +find_previous_siblings() メソッドはマッチする兄弟要素を全て返し、 find_previous_sibling() は最初の一つを返します。:

+
last_link = soup.find("a", id="link3")
+last_link
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+last_link.find_previous_siblings("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+first_story_paragraph = soup.find("p", "story")
+first_story_paragraph.find_previous_sibling("p")
+# <p class="title"><b>The Dormouse's story</b></p>
+
+
+
+
+

find_all_next() / find_next()

+

使い方: find_all_next(name, attrs, text, limit, **kwargs)

+

使い方: find_next(name, attrs, text, **kwargs)

+

これらのメソッドは、HTMLドキュメントのその後にあらわれるタグと文字列の要素全てイテレートして扱うために、 .next_elements メソッドを使います。 +find_all_next() メソッドはマッチするもの全てを返し、 find_next() は最初にマッチしたものを返します。(!要改善):

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_all_next(text=True)
+# [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']
+
+first_link.find_next("p")
+# <p class="story">...</p>
+
+
+

最初の例では、起点となった<a>タグに挟まれている、文字列”Elsie”が返されています。 +2番めの例では、起点となった<a>タグと同じパートじゃないにも関わらず、最後の<p>タグが示されています。 +これらのメソッドでは、問題はフィルターにマッチするか否かと、スタートした要素よりも後にでてきたかということが問われます。(!要改善)

+
+
+

find_all_previous() / find_previous()

+

使い方: find_all_previous(name, attrs, text, limit, **kwargs)

+

使い方: find_previous(name, attrs, text, **kwargs)

+

これらのメソッドは、ドキュメントの起点のタグの前にあらわれるタグと文字列の要素全てをイテレートして扱うために、 .previous_elements メソッドを使います。(!要改善):

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_all_previous("p")
+# [<p class="story">Once upon a time there were three little sisters; ...</p>,
+#  <p class="title"><b>The Dormouse's story</b></p>]
+
+first_link.find_previous("title")
+# <title>The Dormouse's story</title>
+
+
+

find_all_previous("p") は”three sisters”ドキュメントの最初の段落を見つけます。(class=”title”のやつです) +しかし、第2段落でも見つけます。<p>タグは内に起点にした<a>タグを含んでいます。 +驚きすぎないでください。 +我々は、起点のタグより前方に現れた全てのタグを見ているのです。<a>タグを挟んでいる<p>タグは、<a>タグよりも前に示されねばなりません。(!要改善)

+
+
+

CSSセレクタ

+

Beautiful Soupは、よく使われるCSSセレクタをほとんどサポートしています。 +Tag オブジェクトや BeautifulSoup オブジェクトに .select() メソッドで文字列を渡すだけで使えます。

+

タグを見つけるには次のようにします。:

+
soup.select("title")
+# [<title>The Dormouse's story</title>]
+
+soup.select("p nth-of-type(3)")
+# [<p class="story">...</p>]
+
+
+

あるタグより後ろの指定されたタグを見つけます。:

+
soup.select("body a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("html head title")
+# [<title>The Dormouse's story</title>]
+
+
+

あるタグの直後の指定されたタグを見つけます。:

+
soup.select("head > title")
+# [<title>The Dormouse's story</title>]
+
+soup.select("p > a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("p > a:nth-of-type(2)")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+soup.select("p > #link1")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+soup.select("body > a")
+# []
+
+
+

タグの兄弟要素を見つけます。:

+
soup.select("#link1 ~ .sister")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie"  id="link3">Tillie</a>]
+
+soup.select("#link1 + .sister")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+

CSSクラスによってタグを見つけます。:

+
soup.select(".sister")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("[class~=sister]")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

CSSのIDによってタグを見つけます。:

+
soup.select("#link1")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+soup.select("a#link2")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+

指定の属性の有無でタグを見つけます。:

+
soup.select('a[href]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

属性が持つ値によってタグを見つけます。:

+
soup.select('a[href="http://example.com/elsie"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+soup.select('a[href^="http://example.com/"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select('a[href$="tillie"]')
+# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select('a[href*=".com/el"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+
+

languageコードで、マッチさせます。:

+
multilingual_markup = """
+ <p lang="en">Hello</p>
+ <p lang="en-us">Howdy, y'all</p>
+ <p lang="en-gb">Pip-pip, old fruit</p>
+ <p lang="fr">Bonjour mes amis</p>
+"""
+multilingual_soup = BeautifulSoup(multilingual_markup)
+multilingual_soup.select('p[lang|=en]')
+# [<p lang="en">Hello</p>,
+#  <p lang="en-us">Howdy, y'all</p>,
+#  <p lang="en-gb">Pip-pip, old fruit</p>]
+
+
+

このやり方は、CSSセレクタの文法を知っているユーザにとっては、とても便利です。 +これでBeautiful Soup APIの全てのキモを使えるようになりました。 +もしCSSセレクタを使いこなしたいなら、lxmlを使ってみるのもよいでしょう。 +lxmlは処理がとても速く、さらに多くのCSSセレクタをサポートしています。 +しかし、ここではBeautiful Soup APIを使って、シンプルなCSSセレクタの組み合わせるによる方法を説明しました。

+
+
+
+

パースツリーを修正

+

Beautiful Soupの主な強みは、パースツリーの検索するところにあります。 +しかしまた、Beautiful Soupは、ツリーを修正したり、変更したツリーを新しいHTMLやXMLのドキュメントに出力することもできます。

+
+

名前や属性の変更

+

属性 の節でも述べましたが、タグの名前変更、属性値の変更、追加、削除ができます。:

+
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
+tag = soup.b
+
+tag.name = "blockquote"
+tag['class'] = 'verybold'
+tag['id'] = 1
+tag
+# <blockquote class="verybold" id="1">Extremely bold</blockquote>
+
+del tag['class']
+del tag['id']
+tag
+# <blockquote>Extremely bold</blockquote>
+
+
+
+
+

.string の修正

+

Tag オブジェクトの .string を変更すると、そのタグが挟む文字列がその値に変更されます。:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+
+tag = soup.a
+tag.string = "New link text."
+tag
+# <a href="http://example.com/">New link text.</a>
+
+
+

注意点: 変更したタグが他のタグを挟んでいると、それらのタグ全てが破壊されます。

+
+
+

append()

+

Tag.append() により、タグが挟んでいる文字列に追加をすることができます。 +まるでPythonのリストの .append() のように作用します。:

+
soup = BeautifulSoup("<a>Foo</a>")
+soup.a.append("Bar")
+
+soup
+# <html><head></head><body><a>FooBar</a></body></html>
+soup.a.contents
+# [u'Foo', u'Bar']
+
+
+
+
+

BeautifulSoup.new_string() / .new_tag()

+

ドキュメントに文字列を加えたいときは、Pythonの文字列を append() に渡してください。 +もしくは、 factory methodBeautifulSoup.new_string() を呼出してください。:

+
soup = BeautifulSoup("<b></b>")
+tag = soup.b
+tag.append("Hello")
+new_string = soup.new_string(" there")
+tag.append(new_string)
+tag
+# <b>Hello there.</b>
+tag.contents
+# [u'Hello', u' there']
+
+
+

新しいコメントや 他の NavigableString のサブクラスを生成したいときは、 new_string() の第2引数にそのクラスを渡してください。:

+
from bs4 import Comment
+new_comment = soup.new_string("Nice to see you.", Comment)
+tag.append(new_comment)
+tag
+# <b>Hello there<!--Nice to see you.--></b>
+tag.contents
+# [u'Hello', u' there', u'Nice to see you.']
+
+
+

(これはBeautiful Soup 4.2.1 の新機能です)

+

完全に新しいタグを生成したいときは、factory methodの BeautifulSoup.new_tag() を呼び出してください。:

+
soup = BeautifulSoup("<b></b>")
+original_tag = soup.b
+
+new_tag = soup.new_tag("a", href="http://www.example.com")
+original_tag.append(new_tag)
+original_tag
+# <b><a href="http://www.example.com"></a></b>
+
+new_tag.string = "Link text."
+original_tag
+# <b><a href="http://www.example.com">Link text.</a></b>
+
+
+

第1引数のタグ名だけは必須です。

+
+
+

insert()

+

Tag.insert()Tag.append() に似ています。 +違うのは、タグの .contents の最後以外にも、要素を挿入できるという点です。:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+tag = soup.a
+
+tag.insert(1, "but did not endorse ")
+tag
+# <a href="http://example.com/">I linked to but did not endorse <i>example.com</i></a>
+tag.contents
+# [u'I linked to ', u'but did not endorse', <i>example.com</i>]
+
+
+
+
+

insert_before() / insert_after()

+

insert_before() メソッドは、あるタグの直前に、別のタグや文字列を挿入します。:

+
soup = BeautifulSoup("<b>stop</b>")
+tag = soup.new_tag("i")
+tag.string = "Don't"
+soup.b.string.insert_before(tag)
+soup.b
+# <b><i>Don't</i>stop</b>
+
+
+

insert_after() メソッドは、あるタグの直後に、別のタグや文字列を挿入します。:

+
soup.b.i.insert_after(soup.new_string(" ever "))
+soup.b
+# <b><i>Don't</i> ever stop</b>
+soup.b.contents
+# [<i>Don't</i>, u' ever ', u'stop']
+
+
+
+
+

clear()

+

Tag.clear() は、タグが挟んでいるcontentsを削除します。(訳注:要チェック?):

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+tag = soup.a
+
+tag.clear()
+tag
+# <a href="http://example.com/"></a>
+
+
+
+
+

extract()

+

PageElement.extract() はツリーからタグや文字列を除去します。 +返値は、その抽出されたタグや文字列です。:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+i_tag = soup.i.extract()
+
+a_tag
+# <a href="http://example.com/">I linked to</a>
+
+i_tag
+# <i>example.com</i>
+
+print(i_tag.parent)
+None
+
+
+

このとき、2つのパースツリーがあります。1つは BeautifulSoup オブジェクトを根ノードとしたあなたがパースしたドキュメントです。もう1つは、抽出したタグを根ノードとするものです。抽出した要素の子要素を extract でコールできます。:

+
my_string = i_tag.string.extract()
+my_string
+# u'example.com'
+
+print(my_string.parent)
+# None
+i_tag
+# <i></i>
+
+
+
+
+

decompose()

+

Tag.decompose() はパースツリーからタグを除去します。 +そのタグと挟んでいるcontentsを完全に削除します

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+soup.i.decompose()
+
+a_tag
+# <a href="http://example.com/">I linked to</a>
+
+
+
+
+

replace_with()

+

PageElement.replace_with() はツリーからタグと文字列を除去し、 +引数に与えたタグや文字をその代わりに置き換えます。:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+new_tag = soup.new_tag("b")
+new_tag.string = "example.net"
+a_tag.i.replace_with(new_tag)
+
+a_tag
+# <a href="http://example.com/">I linked to <b>example.net</b></a>
+
+
+

replace_with() は置き換えられたタグや文字列を返します。 +それを、調査したり、ツリーの他の部分に加えることができます。

+
+
+

wrap()

+

PageElement.wrap() は、その要素を引数で指定したタグを挟みます。 +新しく挟まれたものを返します。

+
soup = BeautifulSoup("<p>I wish I was bold.</p>")
+soup.p.string.wrap(soup.new_tag("b"))
+# <b>I wish I was bold.</b>
+
+soup.p.wrap(soup.new_tag("div")
+# <div><p><b>I wish I was bold.</b></p></div>
+
+

このメソッドは、Beautiful Soup 4.0.5 からの新機能です。

+
+
+

unwrap()

+

Tag.unwrap()wrap() の反対です。 +それは、タグの中身がなんであれ、それとタグを置き換えます。 +マークアップをはずすのに便利です。(訳注:やりなおし??):

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+a_tag.i.unwrap()
+a_tag
+# <a href="http://example.com/">I linked to example.com</a>
+
+
+

replace_with() のように、 unwrap() は置き換えられたタグを返します。

+
+
+
+

出力

+
+

きれいに出力

+

prettify() メソッドは、BeautifulSoupパースツリーを、1行に1タグのきれいにフォーマットされたUnicode文字列に変換します。:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+soup.prettify()
+# '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/">\n...'
+
+print(soup.prettify())
+# <html>
+#  <head>
+#  </head>
+#  <body>
+#   <a href="http://example.com/">
+#    I linked to
+#    <i>
+#     example.com
+#    </i>
+#   </a>
+#  </body>
+# </html>
+
+
+

prettify() メソッドは、 トップレベルの BeautifulSoup オブジェクトでも、それ以外の Tag オブジェクトでも呼び出すことができます。:

+
print(soup.a.prettify())
+# <a href="http://example.com/">
+#  I linked to
+#  <i>
+#   example.com
+#  </i>
+# </a>
+
+
+
+
+

一行に出力

+

フォーマットされたテキストではなく単なる文字列がほしければ、 BeautifulSoupTag オブジェクトの unicode()str() を呼び出せます。:

+
str(soup)
+# '<html><head></head><body><a href="http://example.com/">I linked to <i>example.com</i></a></body></html>'
+
+unicode(soup.a)
+# u'<a href="http://example.com/">I linked to <i>example.com</i></a>'
+
+
+

str() 関数は、UTF-8にエンコードされた文字列を返します。 +他のオプションを知りたければ、 エンコード をみてください。

+

バイト文字列を得るのに、 encode() を用いることもできます。 +decode() を用いると、Unicodeを得ることができます。

+
+
+

フォーマットを指定

+

Beautiful Soupに、”&lquot;”のようなHTMLエンティティを含んだドキュメントを渡すと、それらはUnicodeキャラクタに変換されます。:

+
soup = BeautifulSoup("&ldquo;Dammit!&rdquo; he said.")
+unicode(soup)
+# u'<html><head></head><body>\u201cDammit!\u201d he said.</body></html>'
+
+
+

そのドキュメントを文字列に変換すると、Unicode文字列はUTF-8キャラクタとしてエンコードされます。 +それを、HTMLエンティティに戻すことはできません。:

+
str(soup)
+# '<html><head></head><body>\xe2\x80\x9cDammit!\xe2\x80\x9d he said.</body></html>'
+
+
+

デフォルトでは、出力するときエスケープされるのは、裸の&と角かっこのみです。 +これらは、”&amp;”,”&lt;”,”&gt”に変換されます。 +そのためBeautifulSoupはうっかり不正確なHTMLやXMLを生成することはありません。:

+
soup = BeautifulSoup("<p>The law firm of Dewey, Cheatem, & Howe</p>")
+soup.p
+# <p>The law firm of Dewey, Cheatem, &amp; Howe</p>
+
+soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
+soup.a
+# <a href="http://example.com/?foo=val1&amp;bar=val2">A link</a>
+
+
+

prettify(), encode(), decode()formatter 属性に値を与えると、出力を変更することができます。 +formatter は、4種類の値をとり得ます。

+

デフォルトでは、 formatter="minimal" です。 +文字列は、Beautiful Soupが正しいHTML/XMLを生成することを十分に保証するように、加工されるだけです。:

+
french = "<p>Il a dit &lt;&lt;Sacr&eacute; bleu!&gt;&gt;</p>"
+soup = BeautifulSoup(french)
+print(soup.prettify(formatter="minimal"))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit &lt;&lt;Sacrテゥ bleu!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

もし、 formatter="html" を渡せば、BSは 可能なときはいつでも、Unicode文字列を HTMLエンティティに変換します。:

+
print(soup.prettify(formatter="html"))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit &lt;&lt;Sacr&eacute; bleu!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

もし、 formatter=None を渡せば、BSは出力においてまったく文字列を修正しません。 +これは、最速のオプションですが、BSが正しくないHTML/XMLを生成することになります。 +次の例をご覧ください。:

+
print(soup.prettify(formatter=None))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit <<Sacrテゥ bleu!>>
+#   </p>
+#  </body>
+# </html>
+
+link_soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
+print(link_soup.a.encode(formatter=None))
+# <a href="http://example.com/?foo=val1&bar=val2">A link</a>
+
+
+

formatter に関数を渡すと、ドキュメントの文字列や属性値のたびに、BSはその関数をコールします。 +関数内で望むことはなんであれできます。 +以下では、formatterは文字列を大文字にコンバートし、他には何もしません。:

+
def uppercase(str):
+    return str.upper()
+
+print(soup.prettify(formatter=uppercase))
+# <html>
+#  <body>
+#   <p>
+#    IL A DIT <<SACRテ BLEU!>>
+#   </p>
+#  </body>
+# </html>
+
+print(link_soup.a.prettify(formatter=uppercase))
+# <a href="HTTP://EXAMPLE.COM/?FOO=VAL1&BAR=VAL2">
+#  A LINK
+# </a>
+
+
+

もしあなたがあなたの関数を書いたなら、あなたは bs4.dammitEntitySubstitution クラスについて知るべきです。 +このクラスは、BSの標準的なformatter をクラスメソッドとして内包します。 +“html” formatterは EntitySubstitution.substitute_html , +“minimal” formatterは EntitySubstitution.substitute_xml です。 +あなたは、これらの関数を、 formatter==htmlformatter==minimal をシュミレーションします。 +しかし、それに加えて他のこともします。

+

これは例です。UnicodeキャラクタをHTMLエンティティに置換します。可能なときはいつでも。 +しかし、 また 全ての文字列を大文字に変換します。:

+
from bs4.dammit import EntitySubstitution
+def uppercase_and_substitute_html_entities(str):
+    return EntitySubstitution.substitute_html(str.upper())
+
+print(soup.prettify(formatter=uppercase_and_substitute_html_entities))
+# <html>
+#  <body>
+#   <p>
+#    IL A DIT &lt;&lt;SACR&Eacute; BLEU!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

最後に一点(最終通告?): もし CData オブジェクトを生成したときは、そのオブジェクト内のテキストは 正確にあるがまま、フォーマットされることなく いつも表されます。 +BSは formatterメソッドを呼出します。あなたがカスタムメソッドを書いた場合にのみ。どういうカスタムメソッド化というと、全てのドキュメント内の文字列やなにかをcountする。しかし、それは返り値を無視します。:

+
from bs4.element import CData
+soup = BeautifulSoup("<a></a>")
+soup.a.string = CData("one < three")
+print(soup.a.prettify(formatter="xml"))
+# <a>
+#  <![CDATA[one < three]]>
+# </a>
+
+
+
+
+

get_text()

+

ドキュメントやタグのテキスト部分だけが取得したいときは、 get_text() メソッドを使います。 +それは、全ドキュメントや下層のタグを、ユニコードの単一文字列として返します。:

+
markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
+soup = BeautifulSoup(markup)
+
+soup.get_text()
+u'\nI linked to example.com\n'
+soup.i.get_text()
+u'example.com'
+
+
+

テキストをまとめる際の区切り文字を指定することができます。:

+
# soup.get_text("|")
+u'\nI linked to |example.com|\n'
+
+
+

各文字列パーツの最初と最後の空白を除去することもできます。:

+
# soup.get_text("|", strip=True)
+u'I linked to|example.com'
+
+
+

空白を除去するのに、 stripped_strings ジェネレーターを使って処理することもできます。:

+
[text for text in soup.stripped_strings]
+# [u'I linked to', u'example.com']
+
+
+
+
+
+

パーサーの指定

+

もし貴方がいくつかのhtmlをパースしたいなら、あなたは、 Beautiful Soup コンストラクタに、マークアップをダンプできる。 +それはたぶんうまくいきます。 +Beautiful Soupはパーサーを選んで、データをパースします。 +しかし、どのパーサーが使われるか変更するために、コンストラクタに渡すいくつかの引数があります

+

1つ目の BeautifulSoup コンストラクタの引数は、 あなたがパースしたいマークアップの、文字列または開いているファイルハンドルです。 +2つ目の引数は、どのように マークアップをぱーすするかについてです。

+

もし何も指定しなかった場合は、インストールされているなかで最高のHTMLパーサーを使います。 +Beautiful Soupは、lxmlのパーサーを最高のものとしています。そして、html5libとPythonの組み込みパーサー。 +あなたは次のうちの一つを指定することで、これを上書きできます。

+
    +
  • パースしたいマークアップの種類: サポートしているのは、”html”, “xml”, “html5”です。
  • +
+
    +
  • パーサーライブラリの名前: オプションとしてサポートしているのは、”lxml”, “html5lib”, (Pythonの組み込みHTMLパーサーである) “html.parser”。
  • +
+

この パーサーのインストール の章は、サポートしているパーサーを比較します。

+

もし適切なパーサーをインストールしていないときは、Beautiful Soupはあなたのリクエストを無視し、違うパーサーを選びます。 +現在、ただ一つサポートされているXMLパーサーは、lxmlです。 +もし、lxmlをインストールしてないとき、XMLの要求はあなたに何も与えませんし、”lxml”へのリクエストも動きません。(要改善!)

+
+

パーサーの違い

+

Beautiful Soupは多くの異なるパーサーに同じインターフェースを提供しています。 +しかし、パーサーはそれぞれは異なります。 +パーサーが異なると、同じドキュメントでも、生成されるパースツリーは異なってきます。 +HTMLパーサーとXMLパーサーには大きな違いがあります。 +以下は、短いドキュメントをHTMLとしてパースしたものです。:

+
BeautifulSoup("<a><b /></a>")
+# <html><head></head><body><a><b></b></a></body></html>
+
+
+

空の<b />タグは、正式なHTMLではないため、パーサーはそれを<b></b>のタグの組に変換します。

+

以下は、同じドキュメントをXMLとしてパースしたものです。 +(これを実行するにはlxmlをインストールしておく必要があります) +<b />タグはそのまま残っており、ドキュメントはXML宣言が<html>タグの代わりに加えられたことに気づいてください。:

+
BeautifulSoup("<a><b /></a>", "xml")
+# <?xml version="1.0" encoding="utf-8"?>
+# <a><b/></a>
+
+
+

HTMLパーサー同士でも、違いはあります。 +完全な形のHTMLドキュメントをBeautiful Soupに与えたときは、その違いは問題になりません。 +あるパーサーは、他のパーサーよりも速いでしょう。 +しかし、それらは全て元のHTMLドキュメントを正確に反映したデータ構造を与えるでしょう。

+

しかし、不完全な形のHTMLドキュメントのときは、異なるパーサーは異なる結果を出力します。 +以下は、lxmlのHTMLパーサーによってパースされた短く不正なドキュメントです。 +ぶらさがっている</p>タグは、単に無視されていることに気づいてください。:

+
BeautifulSoup("<a></p>", "lxml")
+# <html><body><a></a></body></html>
+
+
+

以下は、html5libによってパースされた同じドキュメントです。:

+
BeautifulSoup("<a></p>", "html5lib")
+# <html><head></head><body><a><p></p></a></body></html>
+
+
+

ぶらさがっている</p>タグを無視する代わりに、html5libは、それを開始の<p>タグと組にしました。 +このパーサーはまた、ドキュメントに空の<head>タグも加えました。

+

以下は、Python組み込みのHTMLパーサーで同じドキュメントをパースしたものです。:

+
BeautifulSoup("<a></p>", "html.parser")
+# <a></a>
+
+
+

html5libのように、このパーサーは終わりの</p>タグを無視します。 +html5libとは違い、このパーサーは<body>タグを加えて正しい書式のHTMLドキュメントを作成しようとはしません。 +lxmlとは違い、なんとかして<html>タグを加えようとはしません。

+

“<a></p>”というドキュメントは不正なので、これについての”正しい”処理方法はありません。 +html5libパーサーはhtml5標準のいち部分のテクニックを使います。 +それは、ただしい主張を正しい方法についてします。しかし、これらの3つの方法全て、道理に合っています。(?あとで再チェック)

+

パーサー間の違いは、あなたのスクリプトにも影響するでしょう。 +もし、スクリプトを他の人に配布したり、複数の計算機で実行しようとするならば、 Beautiful Soup コンストラクタについてパーサーを指定するべきです。 +そうすることによって、あなたがパースした方法と違うやりかたでドキュメントをパースする可能性を減らすでしょう。

+
+
+
+

エンコード

+

HTMLやXMLドキュメントは全て、ASCIIやUTF-8のような特定の文字コードで書かれています。 +しかし、BeautifulSoupにドキュメントをロードすると、それらはUnicode型に変換されます。:

+
markup = "<h1>Sacr\xc3\xa9 bleu!</h1>"
+soup = BeautifulSoup(markup)
+soup.h1
+# <h1>Sacré bleu!</h1>
+soup.h1.string
+# u'Sacr\xe9 bleu!'
+
+
+

これは魔法ではありません。Beautiful Soupは Unicode, Dammit を内部でライブラリとして呼び出し、文字コードを判別してUnicodeに変換するのに使っています。 +自動判別された文字コードは、 BeautifulSoup オブジェクトの .original_encoding 属性で参照することができます。:

+
soup.original_encoding
+'utf-8'
+
+
+

Unicode, Dammit はほとんどの場合正しく判別しますが、たまに失敗します。 +たいてい適切に判別しますが、バイト毎の検索の場合は、とてもながい時間がかかります。 +もし、ドキュメントの文字コードが分かっているのなら、失敗や遅延を避けるために、 BeautifulSoup コンストラクタに from_encoding として渡すとよいです。

+

次の例は、ISO-8859-8(訳注:ラテン文字等の文字コード)で書かれたドキュメントです。 +このドキュメントは短いために、Unicode, Dammitはそれが何か判別できず、それをISO-8859-7(訳注:ギリシア文字等の文字コード)と誤認します。:

+
markup = b"<h1>\xed\xe5\xec\xf9</h1>"
+soup = BeautifulSoup(markup)
+soup.h1
+<h1>νεμω</h1>
+soup.original_encoding
+'ISO-8859-7'
+
+

正しい from_encoding を渡すことで、これを正すことができます。:

+
soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
+soup.h1
+<h1>ם ו ל ש</h1>
+soup.original_encoding
+'iso8859-8'
+
+

(通常、UTF-8のドキュメントは複数の文字コードを含むことができますが、) ごくまれに、変換できない文字をユニコードの特殊文字”REPLACEMENT CHARACTER” (U+FFFD,�) に置き換えることがあります。 +Unicode, Dammit がこれを行うときは、同時に、 UnicodeDammitBeautifulSoup オブジェクトの .contains_replacement_characters 属性にTrueをセットします。 +これにより、変換後のユニコードの文字列は、元の文字コードの文字列を正確に表現しておらず、いくつかのデータが損なわれているということがわかります。 +もし、 .contains_replacement_charactersFalse のときは、ドキュメント内に特殊文字�があっても、それは(この段落の�のように)もともとあり、データは損なわれていないということです。

+
+

出力のエンコード

+

Beautiful Soupでドキュメントを出力すると、元のドキュメントがUTF-8でなくても、UTF-8で出力されます。 +次の例は、Latin-1で書かれたドキュメントについてです。:

+
markup = b'''
+ <html>
+  <head>
+   <meta content="text/html; charset=ISO-Latin-1" http-equiv="Content-type" />
+  </head>
+  <body>
+   <p>Sacr\xe9 bleu!</p>
+  </body>
+ </html>
+'''
+
+soup = BeautifulSoup(markup)
+print(soup.prettify())
+# <html>
+#  <head>
+#   <meta content="text/html; charset=utf-8" http-equiv="Content-type" />
+#  </head>
+#  <body>
+#   <p>
+#    Sacrテゥ bleu!
+#   </p>
+#  </body>
+# </html>
+
+
+

<meta>タグは書き換えられ、ドキュメントが現在UTF-8であることを示しています。:

+
.. If you don't want UTF-8, you can pass an encoding into ``prettify()``::
+
+

UTF-8以外で出力したいときは、 prettify() にその文字コードを渡してください。:

+
print(soup.prettify("latin-1"))
+# <html>
+#  <head>
+#   <meta content="text/html; charset=latin-1" http-equiv="Content-type" />
+# ...
+
+
+

Pythonのstr型であるかのように、BeautifulSoup オブジェクトや、その要素のencode()をコールすることができます。:

+
soup.p.encode("latin-1")
+# '<p>Sacr\xe9 bleu!</p>'
+
+soup.p.encode("utf-8")
+# '<p>Sacr\xc3\xa9 bleu!</p>'
+
+
+

あなたが選んだ文字コードでは表せない文字は、XMLエンティティリファレンスの数字に変換されます。 +次の例は、スノーマンのユニコード文字を含んだドキュメントです。:

+
markup = u"<b>\N{SNOWMAN}</b>"
+snowman_soup = BeautifulSoup(markup)
+tag = snowman_soup.b
+
+
+

スノーマンの文字はUTF-8のドキュメントに組み込めます。(それは☃と表示されます。しかし、ISO-Latin-1やASCIIにはその文字がありません。そこで、これらの文字コードでは”&#9731”に変換されます。):

+
print(tag.encode("utf-8"))
+# <b>☃</b>
+
+print tag.encode("latin-1")
+# <b>&#9731;</b>
+
+print tag.encode("ascii")
+# <b>&#9731;</b>
+
+
+
+
+

Unicode, Dammit

+

Beautiful Soup 抜きで、Unicode, Dammitを使えます。 +文字コードがわからないデータを持つときや、Unicodeにそのデータを変換したいときは、それは便利です。:

+
from bs4 import UnicodeDammit
+dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!")
+print(dammit.unicode_markup)
+# Sacré bleu!
+dammit.original_encoding
+# 'utf-8'
+
+
+

Pythonライブラリ chardetcchardet をインストールしていれば、Unicode, Dammitはさらに正確に文字コードを推測できます。:

+
dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"])
+print(dammit.unicode_markup)
+# Sacré bleu!
+dammit.original_encoding
+# 'latin-1'
+
+
+

Unicode, Dammitには、Beautiful Soupが使わない2つの機能があります。

+
+

スマート引用符

+

(訳注: スマート引用符とは、引用符’で左右の向き(open/close)が区別されているもののことです。 +ASCIIコードやシフトJISの引用符は区別されていません。 +[ 参考リンク ])

+

Unicode, Dammitは Microsoftスマート引用符を、HTMLやXMLのエンティティに変換します。:

+
markup = b"<p>I just \x93love\x94 Microsoft Word\x92s smart quotes</p>"
+
+UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup
+# u'<p>I just &ldquo;love&rdquo; Microsoft Word&rsquo;s smart quotes</p>'
+
+UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup
+# u'<p>I just &#x201C;love&#x201D; Microsoft Word&#x2019;s smart quotes</p>'
+
+
+

Microsoftスマート引用符をASCII引用符に変換できます。:

+
UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup
+# u'<p>I just "love" Microsoft Word\'s smart quotes</p>'
+
+
+

できればこの機能を便利に使ってほしいですが、Beautiful Soupはそれを使いません。 +Beautiful Soupは、他の文字と同じように、Microsoftスマート引用符をUnicodeキャラクタに変換するという、デフォルトの振るまいを選びます。:

+
UnicodeDammit(markup, ["windows-1252"]).unicode_markup
+# u'<p>I just \u201clove\u201d Microsoft Word\u2019s smart quotes</p>'
+
+
+
+
+

複数の文字コード

+

ときどき、ほぼUTF-8で書かれているが、一部Microsoftスマート引用符のような文字コードがWindows-1252の文字を含むドキュメントがあります。:

+
snowmen = (u"\N{SNOWMAN}" * 3)
+quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}")
+doc = snowmen.encode("utf8") + quote.encode("windows_1252")
+
+
+

このドキュメントは扱いに困ります。 +スノーマンはUTF-8ですが、スマート引用符はWindows-1252です。 +スノーマンか引用符のどちらかしか表示できません。:

+
print(doc)
+# ☃☃☃�I like snowmen!�
+
+print(doc.decode("windows-1252"))
+# ☃☃☃“I like snowmen!”
+
+
+

ドキュメントをUTF-8としてデコードすると、 UnicodeDecodeError が発生し、Windows-1252でデコードすると意味不明(gibberish?)なことになります。 +幸いなことに、 UnicodeDammit.detwingle() はその文字をpure UTF-8に変換し、それをUnicodeにデコードし、スノーマンと引用符を並べて表示することを許可します。:

+
new_doc = UnicodeDammit.detwingle(doc)
+print(new_doc.decode("utf8"))
+# ☃☃☃“I like snowmen!”
+
+
+

UnicodeDammit.detwingle() UTF-8に埋め込まれたWindows-1252の文字を扱う方法(とその逆)のみを知っています。しかしこれは、よくあるケースではありません。

+

データを BeautifulSoupUnicodeDammit コンストラクタに渡す前に、 UnicodeDammit.detwingle() をコールしなければならないことに注意してください。 +Beautiful Soupは 何らかの単一の文字コードでドキュメントが記されていると想定しています。 +もし、UTF-8とWindows-1252の両方を含むドキュメントを渡したら、ドキュメント全体がWindows-1252と判断しがちです。そして、そしてそのドキュメントの出力は、 ` テ「ヒ愴津「ヒ愴津「ヒ愴停廬 like snowmen!窶拜` のようになります。

+

UnicodeDammit.detwingle() はBeautiful Soup 4.1.0からの機能です。

+
+
+
+
+

ドキュメントの一部をパース

+

あるドキュメントの<a>タグに対してBeautiful Soupを使いたい場合、ドキュメント全部をパースして、その中から<a>タグを探すのは、時間とメモリの無駄です。 +最初にでてくる<a>タグ以外を全て無視すれば、処理は速くなります。 +SoupStrainer クラスは、与えられたドキュメントのどの部分をパースするかを選ぶことができます。 +そのためには、 SoupStrainer を作成し、それを BeautifulSoup コンストラクタに parse_only 属性として渡すだけです。

+

(この機能はhtml5libパーサーを使っているときは、使えないことにご注意ください。 +もしhtml5libを使うときはどんなときでも、ドキュメント全体がパースされます。 +これは、html5libがパースツリーをそのように継続的に再構築するためです。 +もし、ドキュメントの一部がパースツリーに組み込まれてない場合は、それは裏ッシュします。 +それをさけるためには、例において、Beautiful SoupがPythonの組み込みパーサーを利用させてください)

+
+

SoupStrainer

+

SoupStrainer (スープ漉し器)クラスは、 パースツリーを検索: するときの典型的なメソッドである name, attrs, text, and **kwargs をもちます。 +以下は、 SoupStrainer オブジェクトの3通りの例です。:

+
from bs4 import SoupStrainer
+
+only_a_tags = SoupStrainer("a")
+
+only_tags_with_id_link2 = SoupStrainer(id="link2")
+
+def is_short_string(string):
+    return len(string) < 10
+
+only_short_strings = SoupStrainer(text=is_short_string)
+
+
+

ここで、”three sisters”ドキュメントをもう一回とりあげます。 +ドキュメントを SoupStrainer オブジェクトで3通りにパースするので、どうなるかを見てみましょう。:

+
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>
+"""
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify())
+# <a class="sister" href="http://example.com/elsie" id="link1">
+#  Elsie
+# </a>
+# <a class="sister" href="http://example.com/lacie" id="link2">
+#  Lacie
+# </a>
+# <a class="sister" href="http://example.com/tillie" id="link3">
+#  Tillie
+# </a>
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify())
+# <a class="sister" href="http://example.com/lacie" id="link2">
+#  Lacie
+# </a>
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify())
+# Elsie
+# ,
+# Lacie
+# and
+# Tillie
+# ...
+#
+
+
+

SoupStrainer パースツリーを検索 のメソッドに渡すことができます。 +これは、とても便利です。少しだけ説明します。:

+
soup = BeautifulSoup(html_doc)
+soup.find_all(only_short_strings)
+# [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie',
+#  u'\n\n', u'...', u'\n']
+
+
+
+
+
+

トラブルシューティング

+
+

diagnose()

+

もし、Beautiful Soupがドキュメントに何かをしてトラブルになっているときは、どのドキュメントを diagnose() 関数に渡してみてください。(これはBeautiful Soup 4.2.0の新機能です) +Beautiful Soupは、どのようにパーサーがそのドキュメントを扱ったかというレポートを出力し、BeautifulSoupが使っているパーサーが失っているかどうかを教えてくれます。:

+
from bs4.diagnose import diagnose
+data = open("bad.html").read()
+diagnose(data)
+
+# Diagnostic running on Beautiful Soup 4.2.0
+# Python version 2.7.3 (default, Aug  1 2012, 05:16:07)
+# I noticed that html5lib is not installed. Installing it may help.
+# Found lxml version 2.3.2.0
+#
+# Trying to parse your data with html.parser
+# Here's what html.parser did with the document:
+# ...
+
+
+

diagnose()の出力をみてみると、どのように問題を解決すればよいかわかるでしょう。もし、わからなくても、助けをもとめるときに、 diagnose() の出力を貼り付けることができます。

+
+
+

パース時に出るエラー

+

パースエラーには2種類あります。 +1つは、クラッシュです。Beautifuls Soupにドキュメントを読み込ませたときに、例外が発生します。たいていそれは HTMLParser.HTMPParserError です。 +もう1つは、想定外の動作です。Beautiful Soupのパースツリーが、元のドキュメントのパースツリーとかなり違うことがあります。

+

これらのエラーは、たいていBeautiful Soupが原因ではありません。そのように言えるのは、Beautiful Soupがよくできたソフトウェアだからではなく、Beautiful Soupがパース処理のコードを含んでいないためです。 +代わりに、Beautiful Soupは外部のパーサーに頼っています。もしあるパーサーが正しいドキュメントをパースできないときは、他のパーサーを試してみるというのが一番良い対処です。 +パーサーのインストール に、これについての詳細とパーサーの比較が載っています。

+

一番よくみるパースエラーは、 HTMLParser.HTMLParseError: malformed start tag と +HTMLParser.HTMLPraseError: bad end tag でしょう。 +これらはともに、Python組み込みのHTMLパーサーライブラリが返します。 +この場合は、 lxml か html5lib をインストール するとよいです。

+

想定外の動作のエラーで最も多いのは、あると思っていたタグを見つけられないときです。 +見たことあると思いますが、そのとき find_all()[] を返し、 find()None を返します。 +これも、Python組み込みHTMLパーサーにとっては、よくある問題です。やはり、一番よい対処は、 lxml か html5lib をインストール することです。

+
+
+

バージョン違いの問題

+
    +
  • SyntaxError: Invalid syntax (on the line ROOT_TAG_NAME = +u'[document]'): Python 2バージョンのBeautiful Soupを、変換しないでPython 3で実行したためです。
  • +
+
    +
  • ImportError: No module named HTMLParser - Python 2バージョンのBeautiful Soupを、Python 3で実行したためです。
  • +
+
    +
  • ImportError: No module named html.parser - Python 3バージョンのBeautiful Soupを、Python 2で実行したためです。
  • +
+
    +
  • ImportError: No module named BeautifulSoup - Beautiful Soup 3のコードを、BS3がインストールされてない環境で実行したため、またはBeautiful Soup 4のコードをパッケージ名を bs4 に変えずに実行したためです。
  • +
+
    +
  • ImportError: No module named bs4 - Beautiful Soup 4のコードを、BS4がインストールされてない環境で実行したためです。
  • +
+
+
+

XMLのパース

+

デフォルトでは、Beautiful SoupはドキュメントをHTMLとしてパースします。XMLとしてパースするには、 BeautifulSoup コンストラクタの第二引数に、 “xml” を渡します。:

+
soup = BeautifulSoup(markup, "xml")
+
+
+

このためには、 lxml をインストール している必要があります。

+
+
+

その他のパーサーの問題

+
    +
  • If your script works on one computer but not another, it’s probably +because the two computers have different parser libraries +available. For example, you may have developed the script on a +computer that has lxml installed, and then tried to run it on a +computer that only has html5lib installed. See パーサーの違い +for why this matters, and fix the problem by mentioning a +specific parser library in the BeautifulSoup constructor.
  • +
  • Because HTML tags and attributes are case-insensitive, all three HTML +parsers convert tag and attribute names to lowercase. That is, the +markup <TAG></TAG> is converted to <tag></tag>. If you want to +preserve mixed-case or uppercase tags and attributes, you’ll need to +parse the document as XML.
  • +
+
+
+

その他

+
    +
  • UnicodeEncodeError: 'charmap' codec can't encode character +u'\xfoo' in position bar (or just about any other +UnicodeEncodeError) - This is not a problem with Beautiful Soup. +This problem shows up in two main situations. First, when you try to +print a Unicode character that your console doesn’t know how to +display. (See this page on the Python wiki for help.) Second, when +you’re writing to a file and you pass in a Unicode character that’s +not supported by your default encoding. In this case, the simplest +solution is to explicitly encode the Unicode string into UTF-8 with +u.encode("utf8").
  • +
  • KeyError: [attr] - Caused by accessing tag['attr'] when the +tag in question doesn’t define the attr attribute. The most +common errors are KeyError: 'href' and KeyError: +'class'. Use tag.get('attr') if you’re not sure attr is +defined, just as you would with a Python dictionary.
  • +
  • AttributeError: 'ResultSet' object has no attribute 'foo' - This +usually happens because you expected find_all() to return a +single tag or string. But find_all() returns a _list_ of tags +and strings–a ResultSet object. You need to iterate over the +list and look at the .foo of each one. Or, if you really only +want one result, you need to use find() instead of +find_all().
  • +
  • AttributeError: 'NoneType' object has no attribute 'foo' - This +usually happens because you called find() and then tried to +access the .foo` attribute of the result. But in your case, +find() didn’t find anything, so it returned None, instead of +returning a tag or a string. You need to figure out why your +find() call isn’t returning anything.
  • +
+
+
+

パフォーマンス改善

+

Beautiful Soup will never be as fast as the parsers it sits on top +of. If response time is critical, if you’re paying for computer time +by the hour, or if there’s any other reason why computer time is more +valuable than programmer time, you should forget about Beautiful Soup +and work directly atop lxml.

+

That said, there are things you can do to speed up Beautiful Soup. If +you’re not using lxml as the underlying parser, my advice is to +start. Beautiful Soup parses documents +significantly faster using lxml than using html.parser or html5lib.

+

You can speed up encoding detection significantly by installing the +cchardet library.

+

ドキュメントの一部をパース won’t save you much time parsing +the document, but it can save a lot of memory, and it’ll make +searching the document much faster.

+
+
+
+

Beautiful Soup 3

+

Beautiful Soup 3は一つ前のリリースで、すでに開発は停止しています。 +現在でも、全ての主なLinuxディストリビューションに含まれています。:

+

$ apt-get install python-beautifulsoup

+

Pypiでも BeautifulSoup として利用できます。

+

$ easy_install BeautifulSoup

+

$ pip install BeautifulSoup

+

次のリンクからダウンロードできます。tarball of Beautiful Soup 3.2.0.

+

easy_install beautifulsoup , easy_install BeautifulSoup というコマンドでBeautiful Soupをインストールすると、あなたのコードは動きません。 easy_install beautifulsoup4 と入力しましょう。

+

Beautiful Soup 3 のドキュメントはアーカイブされています。

+

日本語版は次のリンクから参照できます。 Beautiful Soup ドキュメント +Beautiful Soup 4での変更点が理解するために、これらのドキュメントを読んでみてください。

+
+

BS4への移行

+

多くのBS3で書かれたコードは、一か所変更するだけでBS4で動きます。パッケージ名を BeautifulSoup から bs4 に変更するだけです。これを、、:

+
from BeautifulSoup import BeautifulSoup
+
+
+

以下のようにします。:

+
from bs4 import BeautifulSoup
+
+
+
    +
  • ImportError “No module named BeautifulSoup” が表示された場合、BS4しかインストールされていないのに、BS3のコードを実行しようとしたのが問題です。
  • +
+
    +
  • ImportError “No module named bs4” が表示された場合、BS3しかインストールされていないのに、BS4のコードを実行しようとしたのが問題です。
  • +
+

BS4はBS3の大部分について後方互換性がありますが、それらのメソッドのほとんどは変更され`PEP 8 規約 <http://www.python.org/dev/peps/pep-0008/>`_ に沿った新しい名前になっています。多くの名前等の変更により、後方互換性の一部が損なわれています。

+

以下は、BS3のコードをBS4に変換するのに知っておくべき事項です。:

+
+

パーサー

+

Beautiful Soup 3 used Python’s SGMLParser, a module that was +deprecated and removed in Python 3.0. Beautiful Soup 4 uses +html.parser by default, but you can plug in lxml or html5lib and +use that instead. See パーサーのインストール for a comparison.

+

Since html.parser is not the same parser as SGMLParser, it +will treat invalid markup differently. Usually the “difference” is +that html.parser crashes. In that case, you’ll need to install +another parser. But sometimes html.parser just creates a different +parse tree than SGMLParser would. If this happens, you may need to +update your BS3 scraping code to deal with the new tree.

+
+
+

メソッド名

+
    +
  • renderContents -> encode_contents
  • +
  • replaceWith -> replace_with
  • +
  • replaceWithChildren -> unwrap
  • +
  • findAll -> find_all
  • +
  • findAllNext -> find_all_next
  • +
  • findAllPrevious -> find_all_previous
  • +
  • findNext -> find_next
  • +
  • findNextSibling -> find_next_sibling
  • +
  • findNextSiblings -> find_next_siblings
  • +
  • findParent -> find_parent
  • +
  • findParents -> find_parents
  • +
  • findPrevious -> find_previous
  • +
  • findPreviousSibling -> find_previous_sibling
  • +
  • findPreviousSiblings -> find_previous_siblings
  • +
  • nextSibling -> next_sibling
  • +
  • previousSibling -> previous_sibling
  • +
+

Some arguments to the Beautiful Soup constructor were renamed for the +same reasons:

+
    +
  • BeautifulSoup(parseOnlyThese=...) -> BeautifulSoup(parse_only=...)
  • +
  • BeautifulSoup(fromEncoding=...) -> BeautifulSoup(from_encoding=...)
  • +
+

I renamed one method for compatibility with Python 3:

+
    +
  • Tag.has_key() -> Tag.has_attr()
  • +
+

I renamed one attribute to use more accurate terminology:

+
    +
  • Tag.isSelfClosing -> Tag.is_empty_element
  • +
+

I renamed three attributes to avoid using words that have special +meaning to Python. Unlike the others, these changes are not backwards +compatible. If you used these attributes in BS3, your code will break +on BS4 until you change them.

+
    +
  • UnicodeDammit.unicode -> UnicodeDammit.unicode_markup
  • +
  • Tag.next -> Tag.next_element
  • +
  • Tag.previous -> Tag.previous_element
  • +
+
+
+

ジェネレーター

+

I gave the generators PEP 8-compliant names, and transformed them into +properties:

+
    +
  • childGenerator() -> children
  • +
  • nextGenerator() -> next_elements
  • +
  • nextSiblingGenerator() -> next_siblings
  • +
  • previousGenerator() -> previous_elements
  • +
  • previousSiblingGenerator() -> previous_siblings
  • +
  • recursiveChildGenerator() -> descendants
  • +
  • parentGenerator() -> parents
  • +
+

So instead of this:

+
for parent in tag.parentGenerator():
+    ...
+
+
+

You can write this:

+
for parent in tag.parents:
+    ...
+
+
+

(But the old code will still work.)

+

Some of the generators used to yield None after they were done, and +then stop. That was a bug. Now the generators just stop.

+

There are two new generators, .strings and +.stripped_strings. .strings yields +NavigableString objects, and .stripped_strings yields Python +strings that have had whitespace stripped.

+
+
+

XML

+

There is no longer a BeautifulStoneSoup class for parsing XML. To +parse XML you pass in “xml” as the second argument to the +BeautifulSoup constructor. For the same reason, the +BeautifulSoup constructor no longer recognizes the isHTML +argument.

+

Beautiful Soup’s handling of empty-element XML tags has been +improved. Previously when you parsed XML you had to explicitly say +which tags were considered empty-element tags. The selfClosingTags +argument to the constructor is no longer recognized. Instead, +Beautiful Soup considers any empty tag to be an empty-element tag. If +you add a child to an empty-element tag, it stops being an +empty-element tag.

+
+
+

エンティティ

+

An incoming HTML or XML entity is always converted into the +corresponding Unicode character. Beautiful Soup 3 had a number of +overlapping ways of dealing with entities, which have been +removed. The BeautifulSoup constructor no longer recognizes the +smartQuotesTo or convertEntities arguments. (Unicode, +Dammit still has smart_quotes_to, but its default is now to turn +smart quotes into Unicode.) The constants HTML_ENTITIES, +XML_ENTITIES, and XHTML_ENTITIES have been removed, since they +configure a feature (transforming some but not all entities into +Unicode characters) that no longer exists.

+

If you want to turn Unicode characters back into HTML entities on +output, rather than turning them into UTF-8 characters, you need to +use an output formatter.

+
+
+

その他

+

Tag.string now operates recursively. If tag A +contains a single tag B and nothing else, then A.string is the same as +B.string. (Previously, it was None.)

+

値が複数のとき like class have lists of strings as +their values, not strings. This may affect the way you search by CSS +class.

+

If you pass one of the find* methods both text and +a tag-specific argument like name, Beautiful Soup will +search for tags that match your tag-specific criteria and whose +Tag.string matches your value for text. It will not find the strings themselves. Previously, +Beautiful Soup ignored the tag-specific arguments and looked for +strings.

+

The BeautifulSoup constructor no longer recognizes the +markupMassage argument. It’s now the parser’s responsibility to +handle markup correctly.

+

The rarely-used alternate parser classes like +ICantBelieveItsBeautifulSoup and BeautifulSOAP have been +removed. It’s now the parser’s decision how to handle ambiguous +markup.

+

The prettify() method now returns a Unicode string, not a bytestring.

+
+
+
+ + +
+
+
+
+
+

Table Of Contents

+ + +

This Page

+ + + + + + + + +
+
+
+
+ + + + diff --git a/doc.html/index.kr.html b/doc.html/index.kr.html new file mode 100644 index 0000000..03319c6 --- /dev/null +++ b/doc.html/index.kr.html @@ -0,0 +1,2476 @@ + + + + + + + + 뷰티플수프 문서 — 뷰티플수프 4.0.0 문서 + + + + + + + + + + + + + + +
+
+
+
+ +
+

뷰티플수프 문서

한글판 johnsonj 2012.11.08 원문 위치 +"The Fish-Footman began by producing from under his arm a great letter, nearly as large as himself." +

뷰티플수프는 HTML과 XML 파일로부터 데이터를 뽑아내기 위한 파이썬 라이브러리이다. 여러분이 선호하는 해석기와 함께 사용하여 일반적인 방식으로 해석 트리를 항해, 검색, 변경할 수 있다. 주로 프로그래머의 수고를 덜어준다.

+

이 지도서에서는 뷰티플수프 4의 중요한 특징들을 예제와 함께 모두 보여준다. 이 라이브러리가 어느 곳에 유용한지, 어떻게 작동하는지, 또 어떻게 사용하는지, 어떻게 원하는대로 바꿀 수 있는지, 예상을 빗나갔을 때 어떻게 해야 하는지를 보여준다.

+

이 문서의 예제들은 파이썬 2.7과 Python 3.2에서 똑 같이 작동한다.

+

혹시 뷰티플수프 3에 관한 문서를 찾고 계신다면 뷰티플수프 3는 더 이상 개발되지 않는다는 사실을 꼭 아셔야겠다. 새로 프로젝트를 시작한다면 뷰티플수프 4를 적극 추천한다. 뷰티플수프 3와 뷰티플수프 4의 차이점은 BS4 코드 이식하기를 참조하자.

+
+

도움 얻기

+

뷰피플수프에 의문이 있거나, 문제에 봉착하면 토론 그룹에 메일을 보내자.

+
+
+
+

바로 시작

+

다음은 이 문서에서 예제로 사용할 HTML 문서이다. 이상한 나라의 앨리스 이야기의 일부이다:

+
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>
+"""
+
+
+

“three sisters” 문서를 뷰피플수프에 넣으면 BeautifulSoup 객체가 나오는데, 이 객체는 문서를 내포된 데이터 구조로 나타낸다:

+
from bs4 import BeautifulSoup
+soup = BeautifulSoup(html_doc)
+
+print(soup.prettify())
+# <html>
+#  <head>
+#   <title>
+#    The Dormouse's story
+#   </title>
+#  </head>
+#  <body>
+#   <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 class="sister" href="http://example.com/elsie" id="link1">
+#     Elsie
+#    </a>
+#    ,
+#    <a class="sister" href="http://example.com/lacie" id="link2">
+#     Lacie
+#    </a>
+#    and
+#    <a class="sister" href="http://example.com/tillie" id="link2">
+#     Tillie
+#    </a>
+#    ; and they lived at the bottom of a well.
+#   </p>
+#   <p class="story">
+#    ...
+#   </p>
+#  </body>
+# </html>
+
+
+

다음은 간단하게 데이터 구조를 항해하는 몇 가지 방법이다:

+
soup.title
+# <title>The Dormouse's story</title>
+
+soup.title.name
+# u'title'
+
+soup.title.string
+# u'The Dormouse's story'
+
+soup.title.parent.name
+# u'head'
+
+soup.p
+# <p class="title"><b>The Dormouse's story</b></p>
+
+soup.p['class']
+# u'title'
+
+soup.a
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+soup.find_all('a')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.find(id="link3")
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+
+

일반적인 과업으로 한 페이지에서 <a> 태그에 존재하는 모든 URL을 뽑아 낼 일이 많다:

+
for link in soup.find_all('a'):
+    print(link.get('href'))
+# http://example.com/elsie
+# http://example.com/lacie
+# http://example.com/tillie
+
+
+

또 다른 과업으로 페이지에서 텍스트를 모두 뽑아낼 일이 많다:

+
print(soup.get_text())
+# The Dormouse's story
+#
+# The Dormouse's story
+#
+# Once upon a time there were three little sisters; and their names were
+# Elsie,
+# Lacie and
+# Tillie;
+# and they lived at the bottom of a well.
+#
+# ...
+
+
+

이것이 여러분이 필요한 것인가? 그렇다면, 계속 읽어 보자.

+
+
+

뷰티플 수프 설치하기

+

데비안이나 우분투 리눅스 최신 버전을 사용중이라면, 시스템 꾸러미 관리자로 뷰티플수프를 설치하자:

+

$ apt-get install python-bs4

+

+뷰티블수프 4는 PyPi를 통하여도 출간되어 있으므로, 시스템 꾸러미 관리자로 설치할 수 없을 경우, easy_install로 설치하거나 +pip로 설치할 수 있다. 꾸러미 이름은 beautifulsoup4이며, 같은 꾸러미로 파이썬 2 그리고 파이썬 3에 작동한다.

+

$ easy_install beautifulsoup4

+

$ pip install beautifulsoup4

+

(이 BeautifulSoup 꾸러미가 혹시 원하는 것이 아니라면. 이전 버전으로 뷰티플수프 3가 있다. 많은 소프트웨에서 BS3를 사용하고 있으므로, 여전히 사용할 수 있다. 그러나 새로 코드를 작성할 생각이라면 beautifulsoup4를 설치하시기 바란다.)

+

easy_installpip도 설치되어 있지 않다면, +뷰티플수프 4 소스를 내려 받아 setup.py로 설치하실 수 있다.

+

$ python setup.py install

+

+다른 모든 것이 실패하더라도, 뷰티플수프 라이센스는 여러분의 어플리케이션에 통채로 꾸려 넣는 것을 허용하므로 전혀 설치할 필요없이 소스를 내려받아 bs4 디렉토리를 통채로 코드베이스에 복사해서 사용하셔도 된다.

+

+본인은 파이썬 2.7과 파이썬 3.2에서 뷰티플수프를 개발하였지만, 다른 최신 버전에도 작동하리라 믿는 바이다.

+
+

설치 이후의 문제

+

뷰티플 수프는 파이썬 2 코드로 꾸려 넣어져 있다. 파이썬 3에 사용하기 위해 설치하면, 파이썬 3 코드로 자동으로 변환된다. 꾸러미가 설치되어 있지 않다면, 당연히 변환되지 않는다. 또한 윈도우즈 머신이라면 잘못된 버전이 설치되어 있다고 보고된다.

+

“No module named HTMLParser”와 같은 ImportError 에러가 일어나면, 파이썬 3 아래에서 파이썬 2 버전의 코드를 실행하고 있기 때문이다.

+

“No module named html.parser”와 같은 ImportError 에러라면, 파이썬 3 버전의 코드를 파이썬 2 아래에서 실행하고 있기 때문이다.

+

두 경우 모두 최선의 선택은 시스템에서 (압축파일을 풀 때 만들어진 디렉토리를 모두 포함하여) 뷰티플수프를 제거하고 다시 설치하는 것이다.

+

다음 ROOT_TAG_NAME = u'[document]' 줄에서 SyntaxError “Invalid syntax”를 맞이한다면, 파이썬 2 코드를 파이썬 3 코드로 변환할 필요가 있다. 이렇게 하려면 다음과 같이 패키지를 설치하거나:

+

$ python3 setup.py install

+

아니면 직접 파이썬의 2to3 변환 스크립트를 +bs4 디렉토리에 실행하면 된다:

+

$ 2to3-3.2 -w bs4

+
+
+

해석기 설치하기

+

뷰티플수프는 파이썬 표준 라이브러리에 포함된 HTML 해석기를 지원하지만, 또 수 많은 제-삼자 파이썬 해석기도 지원한다. 그 중 하나는 lxml 해석기이다. 설정에 따라, 다음 명령어들 중 하나로 lxml을 설치하는 편이 좋을 경우가 있다:

+

$ apt-get install python-lxml

+

$ easy_install lxml

+

$ pip install lxml

+

파이썬 2를 사용중이라면, 또다른 대안은 순수-파이썬 html5lib 해석기를 사용하는 것인데, 이 해석기는 HTML을 웹 브라우저가 해석하는 방식으로 해석한다. 설정에 따라 다음 명령어중 하나로 html5lib를 설치하는 것이 좋을 때가 있다:

+

$ apt-get install python-html5lib

+

$ easy_install html5lib

+

$ pip install html5lib

+

다음 표에 각 해석 라이브러리의 장점과 단점을 요약해 놓았다:

+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
해석기전형적 사용방법장점단점
파이썬의 html.parserBeautifulSoup(markup, "html.parser")
    +
  • 각종 기능 완비
  • +
  • 적절한 속도
  • +
  • 관대함 (파이썬 2.7.3과 3.2에서.)
  • +
+
    +
  • 별로 관대하지 않음 +(파이썬 2.7.3이나 3.2.2 이전 버전에서)
  • +
+
lxml의 HTML 해석기BeautifulSoup(markup, "lxml")
    +
  • 아주 빠름
  • +
  • 관대함
  • +
+
    +
  • 외부 C 라이브러리 의존
  • +
+
lxml의 XML 해석기BeautifulSoup(markup, ["lxml", "xml"]) +BeautifulSoup(markup, "xml")
    +
  • 아주 빠름
  • +
  • 유일하게 XML 해석기 지원
  • +
+
    +
  • 외부 C 라이브러리 의존
  • +
+
html5libBeautifulSoup(markup, html5lib)
    +
  • 아주 관대함
  • +
  • 웹 브라우저의 방식으로 페이지를 해석함
  • +
  • 유효한 HTML5를 생성함
  • +
+
    +
  • 아주 느림
  • +
  • 외부 파이썬 라이브러리 의존
  • +
  • 파이썬 2 전용
  • +
+
+

가능하다면, 속도를 위해 lxml을 설치해 사용하시기를 권장한다. 2.7.3 이전의 파이썬2, 또는3.2.2 이전의 파이썬 3 버전을 사용한다면, lxml을 사용하는 것이 필수이다. 그렇지 않고 구형 버전의 파이썬 내장 HTML 해석기 html5lib는 별로 좋지 않다.

+

문서가 유효하지 않을 경우 해석기마다 다른 뷰티플수프 트리를 생산한다는 사실을 주목하자. 자세한 것은 해석기들 사이의 차이점들을 살펴보자.

+
+
+
+

수프 만들기

+

문서를 해석하려면, 문서를 BeautifulSoup 구성자에 건네주자. 문자열 혹은 열린 파일 핸들을 건네면 된다:

+
from bs4 import BeautifulSoup
+
+soup = BeautifulSoup(open("index.html"))
+
+soup = BeautifulSoup("<html>data</html>")
+
+
+

먼저, 문서는 유니코드로 변환되고 HTML 개체는 유니코드 문자로 변환된다:

+
BeautifulSoup("Sacr&eacute; bleu!")
+<html><head></head><body>Sacré bleu!</body></html>
+
+

다음 뷰티플수프는 문서를 가장 적당한 해석기를 사용하여 해석한다. 특별히 XML 해석기를 사용하라고 지정해 주지 않으면 HTML 해석기를 사용한다. ( XML 해석하기 참조.)

+
+
+

객체의 종류

+

뷰티플수프는 복합적인 HTML 문서를 파이썬 객체로 구성된 복합적인 문서로 변환한다. 그러나 +객체의 종류를 다루는 법만 알면 된다.

+
+

태그

+

Tag 객체는 원래 문서의 XML 태그 또는 HTML 태그에 상응한다:

+
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
+tag = soup.b
+type(tag)
+# <class 'bs4.element.Tag'>
+
+
+

태그는 많은 속성과 메쏘드가 있지만, 그 대부분을 나중에 트리 항해하기 그리고 트리 검색하기에서 다룰 생각이다. 지금은 태그의 가장 중요한 특징인 이름과 속성을 설명한다.

+
+

이름

+

태그마다 이름이 있고, 다음 .name 과 같이 접근할 수 있다:

+
tag.name
+# u'b'
+
+
+

태그의 이름을 바꾸면, 그 변화는 뷰티블수프가 생산한 HTML 조판에 반영된다:

+
tag.name = "blockquote"
+tag
+# <blockquote class="boldest">Extremely bold</blockquote>
+
+
+
+
+

속성

+

태그는 속성을 여러개 가질 수 있다. <b +class="boldest"> 태그는 속성으로 “class”가 있는데 그 값은 +“boldest”이다. 태그의 속성에는 사전처럼 태그를 반복해 접근하면 된다:

+
tag['class']
+# u'boldest'
+
+
+

사전에 .attrs와 같이 바로 접근할 수 있다:

+
tag.attrs
+# {u'class': u'boldest'}
+
+
+

태그의 속성을 추가, 제거, 변경할 수 있다. 역시 태그를 사전처럼 취급해서 처리한다:

+
tag['class'] = 'verybold'
+tag['id'] = 1
+tag
+# <blockquote class="verybold" id="1">Extremely bold</blockquote>
+
+del tag['class']
+del tag['id']
+tag
+# <blockquote>Extremely bold</blockquote>
+
+tag['class']
+# KeyError: 'class'
+print(tag.get('class'))
+# None
+
+
+
+

값이-여럿인 속성

+

HTML 4에서 몇몇 속성은 값을 여러 개 가질 수 있도록 정의된다. HTML 5에서 그 중 2개는 제거되었지만, 몇 가지가 더 정의되었다. 가장 흔한 다중값 속성은 class이다 (다시 말해, 태그가 하나 이상의 CSS 클래스를 가질 수 있다). 다른 것으로는 rel, rev, accept-charset, +headers, 그리고 accesskey가 포함된다. 뷰티플수프는 다중-값 속성의 값들을 리스트로 나타낸다:

+
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
+css_soup.p['class']
+# ["body", "strikeout"]
+
+css_soup = BeautifulSoup('<p class="body"></p>')
+css_soup.p['class']
+# ["body"]
+
+
+

속성에 하나 이상의 값이 있는 것처럼 보이지만, HTML 표준에 정의된 다중-값 속성이 아니라면, 뷰티플수프는 그 속성을 그대로 둔다:

+
id_soup = BeautifulSoup('<p id="my id"></p>')
+id_soup.p['id']
+# 'my id'
+
+
+

태그를 다시 문자열로 바꾸면, 다중-값 속성은 합병된다:

+
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>')
+rel_soup.a['rel']
+# ['index']
+rel_soup.a['rel'] = ['index', 'contents']
+print(rel_soup.p)
+# <p>Back to the <a rel="index contents">homepage</a></p>
+
+
+

문서를 XML로 해석하면, 다중-값 속성은 없다:

+
xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml')
+xml_soup.p['class']
+# u'body strikeout'
+
+
+
+
+
+ +
+

BeautifulSoup

+

+BeautifulSoup 객체 자신은 문서 전체를 대표한다. 대부분의 목적에, 그것을 Tag 객체로 취급해도 좋다. 이것은 곧 트리 항해하기트리 검색하기에 기술된 메쏘드들을 지원한다는 뜻이다.

+

+BeautifulSoup 객체는 실제 HTML 태그나 XML 태그에 상응하지 않기 때문에, 이름도 속성도 없다. 그러나 가끔 그의 이름 .name을 살펴보는 것이 유용할 경우가 있다. 그래서 특별히 +.name에 “[document]”라는 이름이 주어졌다:

+
soup.name
+# u'[document]'
+
+
+
+
+

주석과 기타 특수 문자열들

+

Tag, 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'>
+
+
+

+Comment 객체는 그냥 특별한 유형의 NavigableString이다:

+
comment
+# u'Hey, buddy. Want to buy a used parser'
+
+
+

그러나 HTML 문서의 일부에 나타나면, Comment는 특별한 형태로 화면에 표시된다:

+
print(soup.b.prettify())
+# <b>
+#  <!--Hey, buddy. Want to buy a used parser?-->
+# </b>
+
+
+

뷰티플수프는 XML 문서에 나올만한 것들을 모두 클래스에다 정의한다: CData, ProcessingInstruction, +Declaration, 그리고 Doctype이 그것이다. Comment와 똑같이, 이런 클래스들은 NavigableString의 하위클래스로서 자신의 문자열에 다른 어떤것들을 추가한다. 다음은 주석을 CDATA 블록으로 교체하는 예이다:

+
from bs4 import CData
+cdata = CData("A CDATA block")
+comment.replace_with(cdata)
+
+print(soup.b.prettify())
+# <b>
+#  <![CDATA[A CDATA block]]>
+# </b>
+
+
+
+
+ +
+

트리 탐색하기

+

뷰티플수프에는 해석 트리를 탐색하기 위한 메쏘드들이 많이 정의되어 있지만, 모두 다 거의 비슷하다. 가장 많이 사용되는 두 가지 메쏘드를 설명하는데 시간을 많이 할애할 생각이다: find()find_all()이 그것이다. 다른 메쏘드는 거의 똑 같은 인자를 취한다. 그래서 그것들은 그냥 간략하게 다루겠다.

+

다시 또, “three sisters” 문서를 예제로 사용하자:

+
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)
+
+
+

find_all()과 같이 인자에 여과기를 건네면, 얼마든지 문서에서 관심있는 부분을 뜯어낼 수 있다.

+
+

여과기의 종류

+

find_all()과 유사 메쏘드들에 관하여 자세히 설명하기 전에 먼저, 이런 메쏘드들에 건넬 수 있는 다양한 여과기의 예제들을 보여주고 싶다. 이런 여과기들은 +탐색 API 전체에 걸쳐서 나타나고 또 나타난다. 태그의 이름, 그의 속성, 문자열 텍스트, 또는 이런 것들을 조합하여 여과할 수 있다.

+
+

문자열

+

+가장 단순한 여과기는 문자열이다. 문자열을 탐색 메쏘드에 건네면 뷰티플수프는 그 정확한 문자열에 맞게 부합을 수행한다. 다음 코드는 문서에서 <b> 태그를 모두 찾는다:

+
soup.find_all('b')
+# [<b>The Dormouse's story</b>]
+
+
+

바이트 문자열을 건네면, 뷰티플수프는 그 문자열이 UTF-8로 인코드되어 있다고 간주한다. 이를 피하려면 대신에 유니코드 문자열을 건네면 된다.

+
+
+

정규 표현식

+

정규 표현식 객체를 건네면, 뷰티플수프는 match() 메쏘드를 사용하여 그 정규 표현식에 맞게 여과한다. 다음 코드는 이름이 “b”로 시작하는 태그를 모두 찾는다; 이 경우, <body> 태그와 <b> 태그를 찾을 것이다:

+
import re
+for tag in soup.find_all(re.compile("^b")):
+    print(tag.name)
+# body
+# b
+
+
+

다음 코드는 이름에 ‘t’가 포함된 태그를 모두 찾는다:

+
for tag in soup.find_all(re.compile("t")):
+    print(tag.name)
+# html
+# title
+
+
+
+
+

리스트

+

리스트를 건네면, 뷰티플수프는 그 리스트에 담긴 항목마다 문자열 부합을 수행한다. 다음 코드는 모든 <a> 태그 그리고 모든 <b> 태그를 찾는다:

+
soup.find_all(["a", "b"])
+# [<b>The Dormouse's story</b>,
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+
+
+

True

+

True 값은 참이면 모두 부합시킨다. +다음 코드는 문서에서 태그를 모두 찾지만, 텍스트 문자열은 전혀 찾지 않는다:

+
for tag in soup.find_all(True):
+    print(tag.name)
+# html
+# head
+# title
+# body
+# p
+# b
+# p
+# a
+# a
+# a
+# p
+
+
+
+
+

함수

+

다른 어떤 부합 기준도 마음에 안든다면, 요소를 그의 유일한 인자로 취하는 함수를 정의하면 된다. 함수는 인자가 부합하면 +True를 돌려주고, 그렇지 않으면 False를 돌려주어야 한다.

+

다음은 태그에 “class”속성이 정의되어 있지만 “id” 속성은 없으면 True 를 돌려주는 함수이다:

+
def has_class_but_no_id(tag):
+    return tag.has_key('class') and not tag.has_key('id')
+
+
+

이 함수를 find_all()에 건네면 <p> 태그를 모두 얻게 된다:

+
soup.find_all(has_class_but_no_id)
+# [<p class="title"><b>The Dormouse's story</b></p>,
+#  <p class="story">Once upon a time there were...</p>,
+#  <p class="story">...</p>]
+
+
+

이 함수는 <p> 태그만 얻는다. <a> 태그는 획득하지 않는데, 왜냐하면 “class”와 “id”가 모두 정의되어 있기 때문이다. <html>과 <title>도 얻지 않는데, 왜냐하면 “class”가 정의되어 있지 않기 때문이다.

+

+다음은 태그가 문자열 객체로 둘러 싸여 있으면 True를 돌려주는 함수이다:

+
from bs4 import NavigableString
+def surrounded_by_strings(tag):
+    return (isinstance(tag.next_element, NavigableString)
+            and isinstance(tag.previous_element, NavigableString))
+
+for tag in soup.find_all(surrounded_by_strings):
+    print tag.name
+# p
+# a
+# a
+# a
+# p
+
+
+

이제 탐색 메쏘드들을 자세하게 살펴볼 준비가 되었다.

+
+
+
+

find_all()

+

서명: find_all(name, attrs, recursive, text, limit, **kwargs)

+

+find_all() 메쏘드는 태그의 후손들을 찾아서 지정한 여과기에 부합하면 모두 추출한다. 몇 가지 여과기에서 예제들을 제시했지만, 여기에 몇 가지 더 보여주겠다:

+
soup.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+soup.find_all("p", "title")
+# [<p class="title"><b>The Dormouse's story</b></p>]
+
+soup.find_all("a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.find_all(id="link2")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+import re
+soup.find(text=re.compile("sisters"))
+# u'Once upon a time there were three little sisters; and their names were\n'
+
+
+

어떤 것은 익숙하지만, 다른 것들은 새로울 것이다. text 혹은 id에 값을 건넨다는 것이 무슨 뜻인가? 왜 다음 +find_all("p", "title")은 CSS 클래스가 “title”인 <p> 태그를 찾는가? + find_all()에 건넨 인자들을 살펴보자.

+
+

name 인자

+

인자를 name에 건네면 뷰티플수프는 특정 이름을 가진 태그에만 관심을 가진다. 이름이 부합되지 않는 태그와 마찬가지로, 텍스트 문자열은 무시된다.

+

다음은 가장 단순한 사용법이다:

+
soup.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+
+

여과기의 종류에서 보았듯이 name에 건넨 값이 문자열, 정규 표현식, 리스트, 함수, 또는 True 값일 수 있다는 사실을 기억하자.

+
+
+

키워드 인자

+

인지되지 않는 인자는 한 태그의 속성중 하나에 대한 여과기로 변환된다. + +id라는 인자에 대하여 값을 하나 건네면, 뷰티플수프는 각 태그의 ‘id’속성에 대하여 걸러낸다:

+
soup.find_all(id='link2')
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+

href에 대하여 값을 건네면, 뷰티플수프는 각 태그의 ‘href’속성에 대하여 걸러낸다:

+
soup.find_all(href=re.compile("elsie"))
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+
+

문자열, 정규 표현식, 리스트, 함수, 또는 True 값에 기반하여 속성을 걸러낼 수 있다.

+

다음 코드는 그 값이 무엇이든 상관없이, id 속성을 가진 태그를 모두 찾는다:

+
soup.find_all(id=True)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

하나 이상의 키워드 인자를 건네면 한 번에 여러 값들을 걸러낼 수 있다:

+
soup.find_all(href=re.compile("elsie"), id='link1')
+# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
+
+
+
+
+

CSS 클래스로 탐색하기

+

특정 CSS 클래스를 가진 태그를 탐색하면 아주 유용하지만, CSS 속성의 이름인 “class”는 파이썬에서 예약어이다. 키워드 인자로 class를 사용하면 구문 에러를 만나게 된다. 뷰티플 4.1.2 부터, CSS 클래스로 검색할 수 있는데 class_ 키워드 인자를 사용하면 된다:

+
soup.find_all("a", class_="sister")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

다른 키워드 인자와 마찬가지로, class_에 문자열, 정규 표현식, 함수, 또는 True를 건넬 수 있다:

+
soup.find_all(class_=re.compile("itl"))
+# [<p class="title"><b>The Dormouse's story</b></p>]
+
+def has_six_characters(css_class):
+    return css_class is not None and len(css_class) == 6
+
+soup.find_all(class_=has_six_characters)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

기억하자. 하나의 태그에 그의 “class” 속성에 대하여 값이 여러개 있을 수 있다. 특정 CSS 클래스에 부합하는 태그를 탐색할 때, 그의 CSS 클래스들 모두에 대하여 부합을 수행하는 것이다:

+
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
+css_soup.find_all("p", class_="strikeout")
+# [<p class="body strikeout"></p>]
+
+css_soup.find_all("p", class_="body")
+# [<p class="body strikeout"></p>]
+
+
+

+class 속성의 정확한 문자열 값을 탐색할 수도 있다:

+
css_soup.find_all("p", class_="body strikeout")
+# [<p class="body strikeout"></p>]
+
+
+

+그러나 문자열 값을 변형해서 탐색하면 작동하지 않는다:

+
css_soup.find_all("p", class_="strikeout body")
+# []
+
+
+

class_를 위한 간편한 방법이 뷰티플수프 모든 버전에 존재한다. find()-유형의 메쏘드에 건네는 두 번째 인자는 attrs인데, 문자열을 attrs에 건네면 그 문자열을 CSS 클래스처럼 탐색한다:

+
soup.find_all("a", "sister")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

정규 표현식, 함수 또는 사전을 제외하고 True–유형으로도 건넬 수 있다. 무엇을 건네든지 그 CSS 클래스를 탐색하는데 사용된다. class_ 키워드 인자에 건넬 때와 똑같다:

+
soup.find_all("p", re.compile("itl"))
+# [<p class="title"><b>The Dormouse's story</b></p>]
+
+
+

사전을 attrs에 건네면, 단지 그 CSS 클래스만 아니라 한번에 많은 HTML 속성을 탐색할 수 있다. 다음 코드 두 줄은 동등하다:

+
soup.find_all(href=re.compile("elsie"), id='link1')
+soup.find_all(attrs={'href' : re.compile("elsie"), 'id': 'link1'})
+
+
+

이것은 별로 유용한 특징은 아니다. 왜냐하면 보통 키워드 인자를 사용하는 편이 더 쉽기 때문이다.

+
+
+

text 인자

+

+text 인자로 태그 대신 문자열을 탐색할 수 있다. name과 키워드 인자에서처럼, 문자열, 정규 표현식, 리스트, 함수, 또는 True 값을 건넬 수 있다. +다음은 몇 가지 예이다:

+
soup.find_all(text="Elsie")
+# [u'Elsie']
+
+soup.find_all(text=["Tillie", "Elsie", "Lacie"])
+# [u'Elsie', u'Lacie', u'Tillie']
+
+soup.find_all(text=re.compile("Dormouse"))
+[u"The Dormouse's story", u"The Dormouse's story"]
+
+def is_the_only_string_within_a_tag(s):
+    """Return True if this string is the only child of its parent tag."""
+    return (s == s.parent.string)
+
+soup.find_all(text=is_the_only_string_within_a_tag)
+# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']
+
+
+

+text가 문자열 찾기에 사용되지만, 태그를 찾는 인자와 결합해 사용할 수 있다: 뷰티플수프는 text에 대한 값에 자신의 .string이 부합하는 태그를 모두 찾는다. + +다음 코드는 자신의 .string이 “Elsie”인 <a> 태그를 찾는다:

+
soup.find_all("a", text="Elsie")
+# [<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>]
+
+
+
+
+

limit 인자

+

find_all() 메쏘드는 여과기에 부합하는 문자열과 태그를 모두 돌려준다. 이런 방법은 문서가 방대하면 시간이 좀 걸릴 수 있다. 결과가 모조리 필요한 것은 아니라면, limit에 숫자를 건넬 수 있다. 이 방법은 SQL에서의 LIMIT 키워드와 정확히 똑같이 작동한다. 뷰티플수프에게 특정 횟수를 넘어서면 결과 수집을 중지하라고 명령한다.

+

“three sisters” 문서에 링크가 세 개 있지만, 다음 코드는 앞의 두 링크만 찾는다:

+
soup.find_all("a", limit=2)
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+
+
+

recursive 인자

+

mytag.find_all()를 호출하면, 뷰티플수프는 mytag의 후손을 모두 조사한다: 그의 자손, 그 자손의 자손, 그리고 등등. 뷰티플수프에게 직계 자손만 신경쓰라고 시키고 싶다면, recursive=False를 건네면 된다. 다음에 차이점을 살펴보자:

+
soup.html.find_all("title")
+# [<title>The Dormouse's story</title>]
+
+soup.html.find_all("title", recursive=False)
+# []
+
+
+

다음은 예제 문서의 일부이다:

+
<html>
+ <head>
+  <title>
+   The Dormouse's story
+  </title>
+ </head>
+...
+
+

+<title> 태그는 <html> 태그 아래에 있지만, <html> 태그 바로 아래에 있는 것은 아니다: <head> 태그가 사이에 있다. 뷰티플수프는 <html> 태그의 모든 후손을 찾아 보도록 허용해야만 <title> 태그를 발견한다. 그러나 recursive=False가 검색을 +<html> 태그의 직접 자손으로 제한하기 때문에, 아무것도 찾지 못한다.

+

뷰티플수프는 트리-탐색 메쏘드들을 다양하게 제공한다 (아래에 다룸). 대부분 find_all()과 같은 인자를 취한다: name, +attrs, text, limit, 그리고 키워드 인자를 취한다. 그러나 recursive 인자는 다르다: find_all()find()만 유일하게 지원한다. recursive=Falsefind_parents() 같은 인자에 건네면 별로 유용하지 않을 것이다.

+
+
+
+

태그를 호출하는 것은 find_all()을 호출하는 것과 똑같다

+

+find_all()는 뷰티플수프 탐색 API에서 가장 많이 사용되므로, 그에 대한 간편 방법을 사용할 수 있다. BeautifulSoup 객체나 Tag 객체를 마치 함수처럼 다루면, 그 객체에 대하여 find_all()를 호출하는 것과 똑같다. 다음 코드 두 줄은 동등하다:

+
soup.find_all("a")
+soup("a")
+
+
+

다음 두 줄도 역시 동등하다:

+
soup.title.find_all(text=True)
+soup.title(text=True)
+
+
+
+
+

find()

+

서명: find(name, attrs, recursive, text, **kwargs)

+

+find_all() 메쏘드는 전체 문서를 훓어서 결과를 찾지만, 어떤 경우는 결과 하나만 원할 수도 있다. 문서에 오직 <body> 태그가 하나 뿐임을 안다면, 전체 문서를 훓어 가면서 더 찾는 것은 시간 낭비이다. find_all 메쏘드를 호출할 때마다, limit=1을 건네기 보다는 find() 메쏘드를 사용하는 편이 좋다. 다음 코드 두 줄은 거의 동등하다:

+
soup.find_all('title', limit=1)
+# [<title>The Dormouse's story</title>]
+
+soup.find('title')
+# <title>The Dormouse's story</title>
+
+
+

유일한 차이점은 find_all() 메쏘드가 단 한개의 결과만 담고 있는 리스트를 돌려주고, find()는 그냥 그 결과를 돌려준다는 점이다.

+

find_all()이 아무것도 찾을 수 없다면, 빈 리스트를 돌려준다. find()가 아무것도 찾을 수 없다면, None을 돌려준다:

+
print(soup.find("nosuchtag"))
+# None
+
+
+

+태그 이름을 사용하여 항해하기에서 soup.head.title 트릭을 기억하시는지? 그 트릭은 반복적으로 find() 를 호출해서 작동한다:

+
soup.head.title
+# <title>The Dormouse's story</title>
+
+soup.find("head").find("title")
+# <title>The Dormouse's story</title>
+
+
+
+
+

find_parents() 그리고 find_parent()

+

서명: find_parents(name, attrs, text, limit, **kwargs)

+

서명: find_parent(name, attrs, text, **kwargs)

+

+많은 시간을 할애해 find_all()과 +find()를 다루었다. 뷰티플수프 API에는 트리 탐색을 위해 다른 메쏘드가 열가지 정의되어 있지만, 걱정하지 말자. 이런 메쏘드중 다섯가지는 기본적으로 find_all()과 똑같고, 다른 다섯가지는 기본적으로 find()와 똑같다. 유일한 차이점은 트리의 어떤 부분을 검색할 것인가에 있다.

+

+먼저 find_parents()와 +find_parent()를 살펴보자. find_all()find()는 트리를 내려 오면서, 태그의 후손들을 찾음을 기억하자. 다음 메쏘드들은 정 반대로 일을 한다: 트리를 위로 올라가며, 한 태그의 (또는 문자열의) 부모를 찾는다. 시험해 보자.“three daughters” 문서 깊숙히 묻힌 문자열부터 시작해 보자:

+
a_string = soup.find(text="Lacie")
+a_string
+# u'Lacie'
+
+a_string.find_parents("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+a_string.find_parent("p")
+# <p class="story">Once upon a time there were three little sisters; and their names were
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
+#  and they lived at the bottom of a well.</p>
+
+a_string.find_parents("p", class="title")
+# []
+
+

세가지 <a> 태그 중 하나는 해당 문자열의 직계 부모이다. 그래서 탐색해서 그것을 찾는다. 세가지 <p> 태그 중 하나는 그 문자열의 방계 부모이고, 그것도 역시 잘 탐색한다. CSS 클래스가“title”인 <p> 태그가 문서 어딘가에 존재하지만, 그것은 이 문자열의 부모가 아니므로, find_parents()로 부모를 찾을 수 없다.

+

아마도 find_parent()find_parents(), 그리고 앞서 언급한 .parent.parents 속성 사이에 관련이 있으리라 짐작했을 것이다. 이 관련은 매우 강력하다. 이 탐색 메쏘드들은 실제로 .parents로 부모들을 모두 찾아서, 제공된 여과기준에 부합하는지 하나씩 점검한다.

+
+
+

find_next_siblings() 그리고 find_next_sibling()

+

서명: find_next_siblings(name, attrs, text, limit, **kwargs)

+

서명: find_next_sibling(name, attrs, text, **kwargs)

+

이 메쏘드들은 .next_siblings을 사용하여 트리에서 한 요소의 나머지 형제들을 반복한다. find_next_siblings() 메쏘드는 부합하는 형제들을 모두 돌려주고, find_next_sibling() 메쏘드는 그 중 첫 째만 돌려준다:

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_next_siblings("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+first_story_paragraph = soup.find("p", "story")
+first_story_paragraph.find_next_sibling("p")
+# <p class="story">...</p>
+
+
+
+
+

find_previous_siblings() 그리고 find_previous_sibling()

+

서명: find_previous_siblings(name, attrs, text, limit, **kwargs)

+

서명: find_previous_sibling(name, attrs, text, **kwargs)

+

+이 메쏘드들은 .previous_siblings를 사용하여 트리에서 한 원소의 앞에 나오는 형제들을 반복한다. find_previous_siblings() 메쏘는 부합하는 형제들을 모두 돌려주고, find_previous_sibling()는 첫 째만 돌려준다:

+
last_link = soup.find("a", id="link3")
+last_link
+# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
+
+last_link.find_previous_siblings("a")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+first_story_paragraph = soup.find("p", "story")
+first_story_paragraph.find_previous_sibling("p")
+# <p class="title"><b>The Dormouse's story</b></p>
+
+
+
+
+

find_all_next() 그리고 find_next()

+

서명: find_all_next(name, attrs, text, limit, **kwargs)

+

서명: find_next(name, attrs, text, **kwargs)

+

+이 메쏘드들은 .next_elements를 사용하여 문서에서 한 태그의 뒤에 오는 태그이든 문자열이든 무엇이든지 반복한다. find_all_next() 메쏘드는 부합하는 것들을 모두 돌려주고, find_next()는 첫 번째 부합하는 것만 돌려준다:

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_all_next(text=True)
+# [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']
+
+first_link.find_next("p")
+# <p class="story">...</p>
+
+
+

첫 예제에서, 문자열 “Elsie”가 나타났다. 물론 그 안에 우리가 시작했던 <a> 태그 안에 포함되어 있음에도 불구하고 말이다. + +두 번째 예제를 보면, 문서의 마지막 <p> 태그가 나타났다. 물론 트리에서 우리가 시작했던 <a> 태그와 같은 부분에 있지 않음에도 불구하고 말이다. 이런 메쏘드들에게, 유일한 관심 사항은 원소가 여과 기준에 부합하는가 그리고 시작 원소 말고 나중에 문서에 나타나는가이다.

+
+
+

find_all_previous() 그리고 find_previous()

+

서명: find_all_previous(name, attrs, text, limit, **kwargs)

+

서명: find_previous(name, attrs, text, **kwargs)

+

+이 메쏘드들은 .previous_elements를 사용하여 문서에서 앞에 오는 태그나 문자열들을 반복한다. find_all_previous() 메쏘드는 부합하는 모든 것을 돌려주고, +find_previous()는 첫 번째 부합만 돌려준다:

+
first_link = soup.a
+first_link
+# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
+
+first_link.find_all_previous("p")
+# [<p class="story">Once upon a time there were three little sisters; ...</p>,
+#  <p class="title"><b>The Dormouse's story</b></p>]
+
+first_link.find_previous("title")
+# <title>The Dormouse's story</title>
+
+
+

find_all_previous("p")를 호출하면 문서에서 첫 번째 문단(class=”title”)을 찾지만, 두 번째 문단 <p> 태그도 찾는다. 이 안에 우리가 시작한 <a> 태그가 들어 있다. 이것은 그렇게 놀랄 일이 아니다: 시작한 위치보다 더 앞에 나타나는 태그들을 모두 찾고 있는 중이다. +<a> 태그가 포함된 <p> 태그는 자신 안에 든 <a> 태그보다 먼저 나타나는 것이 당연하다.

+
+
+

CSS 선택자

+

뷰티플수프는 CSS 선택자 표준의 부분집합을 지원한다. 그냥 문자열로 선택자를 구성하고 그것을 Tag.select() 메쏘드 또는 BeautifulSoup 객체 자체에 건네면 된다.

+

다음과 같이 태그를 검색할 수 있다:

+
soup.select("title")
+# [<title>The Dormouse's story</title>]
+
+
+

다른 태그 아래의 태그를 찾을 수 있다:

+
soup.select("body a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("html head title")
+# [<title>The Dormouse's story</title>]
+
+
+

다른 태그 바로 아래에 있는 태그를 찾을 수 있다:

+
soup.select("head > title")
+# [<title>The Dormouse's story</title>]
+
+soup.select("p > a")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("body > a")
+# []
+
+
+

CSS 클래스로 태그를 찾는다:

+
soup.select(".sister")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select("[class~=sister]")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

ID로 태그를 찾는다:

+
soup.select("#link1")
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+soup.select("a#link2")
+# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
+
+
+

속성이 존재하는지 테스트 한다:

+
soup.select('a[href]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+
+

속성 값으로 태그를 찾는다:

+
soup.select('a[href="http://example.com/elsie"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+soup.select('a[href^="http://example.com/"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
+#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
+#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select('a[href$="tillie"]')
+# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
+
+soup.select('a[href*=".com/el"]')
+# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
+
+
+

언어 코덱을 일치 시킨다:

+
multilingual_markup = """
+ <p lang="en">Hello</p>
+ <p lang="en-us">Howdy, y'all</p>
+ <p lang="en-gb">Pip-pip, old fruit</p>
+ <p lang="fr">Bonjour mes amis</p>
+"""
+multilingual_soup = BeautifulSoup(multilingual_markup)
+multilingual_soup.select('p[lang|=en]')
+# [<p lang="en">Hello</p>,
+#  <p lang="en-us">Howdy, y'all</p>,
+#  <p lang="en-gb">Pip-pip, old fruit</p>]
+
+
+

이것은 CSS 선택자 구문을 알고 있는 사용자에게 유용하다. 이 모든 일들을 뷰티플수프 API로 할 수 있다. CSS 선택자만 필요하다면, lxml을 직접 사용하는 편이 좋을 것이다. 왜냐하면, 더 빠르기 때문이다. 그러나 이렇게 하면 간단한 CSS 선택자들을 뷰티플수프 API와 조합해 사용할 수 있다.

+
+
+
+

트리 변형하기

+

뷰티플수프의 강점은 해석 트리를 검색 하는데에 있다. 그러나 또한 해석 트리를 변형해서 새로운 HTML 또는 XML 문서로 저장할 수도 있다.

+
+

태그 이름과 속성 바꾸기

+

이에 관해서는 속성 부분에서 다룬 바 있지만, 다시 반복할 가치가 있다. 태그 이름을 바꾸고 그의 속성 값들을 바꾸며, 속성을 새로 추가하고, 속성을 삭제할 수 있다:

+
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
+tag = soup.b
+
+tag.name = "blockquote"
+tag['class'] = 'verybold'
+tag['id'] = 1
+tag
+# <blockquote class="verybold" id="1">Extremely bold</blockquote>
+
+del tag['class']
+del tag['id']
+tag
+# <blockquote>Extremely bold</blockquote>
+
+
+
+
+

.string 변경하기

+

태그의 .string 속성을 설정하면, 태그의 내용이 주어진 문자열로 교체된다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+
+tag = soup.a
+tag.string = "New link text."
+tag
+# <a href="http://example.com/">New link text.</a>
+
+
+

주의하자: 태그에 또 다른 태그가 들어 있다면, 그 태그는 물론 모든 내용이 사라진다.

+
+
+

append()

+

Tag.append()로 태그에 내용을 추가할 수 있다. 파이썬 리스트에 .append()를 호출한 것과 똑같이 작동한다:

+
soup = BeautifulSoup("<a>Foo</a>")
+soup.a.append("Bar")
+
+soup
+# <html><head></head><body><a>FooBar</a></body></html>
+soup.a.contents
+# [u'Foo', u'Bar']
+
+
+
+
+

BeautifulSoup.new_string() 그리고 .new_tag()

+

문자열을 문서에 추가하고 싶다면, 파이썬 문자열을 append()에 건네기만 하면 된다. 아니면 +BeautifulSoup.new_string() 공장 메쏘드를 호출하면 된다:

+
soup = BeautifulSoup("<b></b>")
+tag = soup.b
+tag.append("Hello")
+new_string = soup.new_string(" there")
+tag.append(new_string)
+tag
+# <b>Hello there.</b>
+tag.contents
+# [u'Hello', u' there']
+
+
+

완전히 새로 태그를 만들어야 한다면 어떻게 할까? 최선의 해결책은 BeautifulSoup.new_tag() 공장 메쏘드를 호출하는 것이다:

+
soup = BeautifulSoup("<b></b>")
+original_tag = soup.b
+
+new_tag = soup.new_tag("a", href="http://www.example.com")
+original_tag.append(new_tag)
+original_tag
+# <b><a href="http://www.example.com"></a></b>
+
+new_tag.string = "Link text."
+original_tag
+# <b><a href="http://www.example.com">Link text.</a></b>
+
+
+

오직 첫 번째 인자, 즉 태그 이름만 있으면 된다.

+
+
+

insert()

+

Tag.insert()Tag.append()와 거의 같은데, 단, 새 요소가 반드시 그의 부모의 .contents 끝에 갈 필요는 없다. 원하는 위치 어디든지 삽입된다. 파이썬 리스트의 .insert()와 똑같이 작동한다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+tag = soup.a
+
+tag.insert(1, "but did not endorse ")
+tag
+# <a href="http://example.com/">I linked to but did not endorse <i>example.com</i></a>
+tag.contents
+# [u'I linked to ', u'but did not endorse', <i>example.com</i>]
+
+
+
+
+

insert_before() 그리고 insert_after()

+

+insert_before() 메쏘드는 태그나 문자열을 해석 트리에서 어떤 것 바로 앞에 삽입한다:

+
soup = BeautifulSoup("<b>stop</b>")
+tag = soup.new_tag("i")
+tag.string = "Don't"
+soup.b.string.insert_before(tag)
+soup.b
+# <b><i>Don't</i>stop</b>
+
+
+

+insert_after() 메쏘드는 해석 트리에서 다른 어떤 것 바로 뒤에 나오도록 태그나 문자열을 이동시킨다:

+
soup.b.i.insert_after(soup.new_string(" ever "))
+soup.b
+# <b><i>Don't</i> ever stop</b>
+soup.b.contents
+# [<i>Don't</i>, u' ever ', u'stop']
+
+
+
+
+

clear()

+

Tag.clear()은 태그의 내용을 제거한다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+tag = soup.a
+
+tag.clear()
+tag
+# <a href="http://example.com/"></a>
+
+
+
+
+

extract()

+

PageElement.extract()는 해석 트리에서 태그나 문자열을 제거한다. 추출하고 남은 태그나 문자열을 돌려준다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+i_tag = soup.i.extract()
+
+a_tag
+# <a href="http://example.com/">I linked to</a>
+
+i_tag
+# <i>example.com</i>
+
+print(i_tag.parent)
+None
+
+
+

이 시점에서 두 가지 해석 트리를 가지는 효과가 있다: 하나는 문서를 해석하는데 사용된 BeautifulSoup 객체에 뿌리를 두고, 또 하나는 추출된 그 태그에 뿌리를 둔다. 더 나아가 추출한 요소의 자손들에다 extract를 호출할 수 있다:

+
my_string = i_tag.string.extract()
+my_string
+# u'example.com'
+
+print(my_string.parent)
+# None
+i_tag
+# <i></i>
+
+
+
+
+

decompose()

+

Tag.decompose()는 태그를 트리에서 제거한 다음, 그와 그의 내용물을 완전히 파괴한다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+soup.i.decompose()
+
+a_tag
+# <a href="http://example.com/">I linked to</a>
+
+
+
+
+

replace_with()

+

PageElement.replace_with()는 트리에서 태그나 문자열을 제거하고 그것을 지정한 태그나 문자열로 교체한다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+new_tag = soup.new_tag("b")
+new_tag.string = "example.net"
+a_tag.i.replace_with(new_tag)
+
+a_tag
+# <a href="http://example.com/">I linked to <b>example.net</b></a>
+
+
+

replace_with()는 교체된 후의 태그나 문자열을 돌려준다. 그래서 검사해 보거나 다시 트리의 다른 부분에 추가할 수 있다.

+
+
+

wrap()

+

PageElement.wrap()는 지정한 태그에 요소를 둘러싸서 새로운 포장자를 돌려준다:

+
soup = BeautifulSoup("<p>I wish I was bold.</p>")
+soup.p.string.wrap(soup.new_tag("b"))
+# <b>I wish I was bold.</b>
+
+soup.p.wrap(soup.new_tag("div")
+# <div><p><b>I wish I was bold.</b></p></div>
+
+

다음 메쏘드는 뷰티플수프 4.0.5에 새로 추가되었다.

+
+
+

unwrap()

+

Tag.unwrap()wrap()의 반대이다. 태그를 그 태그 안에 있는 것들로 교체한다. 조판을 걷어내 버릴 때 좋다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+a_tag = soup.a
+
+a_tag.i.unwrap()
+a_tag
+# <a href="http://example.com/">I linked to example.com</a>
+
+
+

replace_with()처럼, unwrap()은 교체된 후의 태그를 돌려준다.

+

(이전 뷰티플수프 버전에서, unwrap()replace_with_children()이라고 불리웠으며, 그 이름은 여전히 작동한다.)

+
+
+
+

출력

+
+

예쁘게-인쇄하기

+

prettify() 메쏘드는 뷰티플수프 해석 트리를 멋지게 모양을 낸 유니코드 문자열로 변환한다. HTML/XML 태그마다 따로따로 한 줄에 표시된다:

+
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
+soup = BeautifulSoup(markup)
+soup.prettify()
+# '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/">\n...'
+
+print(soup.prettify())
+# <html>
+#  <head>
+#  </head>
+#  <body>
+#   <a href="http://example.com/">
+#    I linked to
+#    <i>
+#     example.com
+#    </i>
+#   </a>
+#  </body>
+# </html>
+
+
+

최상위 BeautifulSoup 객체에 prettify()를 호출할 수 있으며, 또는 Tag 객체에 얼마든지 호출할 수 있다:

+
print(soup.a.prettify())
+# <a href="http://example.com/">
+#  I linked to
+#  <i>
+#   example.com
+#  </i>
+# </a>
+
+
+
+
+

있는-그대로 인쇄하기

+

멋진 모양 말고 그냥 문자열을 원한다면, BeautifulSoup 객체, 또는 그 안의 Tagunicode() 또는 str()을 호출하면 된다:

+
str(soup)
+# '<html><head></head><body><a href="http://example.com/">I linked to <i>example.com</i></a></body></html>'
+
+unicode(soup.a)
+# u'<a href="http://example.com/">I linked to <i>example.com</i></a>'
+
+
+

str() 함수는 UTF-8로 인코드된 문자열을 돌려준다. 다른 옵션은 인코딩을 살펴보자.

+

encode()를 호출하면 bytestring을 얻을 수 있고, decode()로는 유니코드를 얻는다.

+
+
+

출력 포맷터

+

뷰티플수프 문서에 “&lquot;”와 같은 HTML 개체가 들어 있다면, 그 개체들은 유니코드 문자로 변환된다:

+
soup = BeautifulSoup("&ldquo;Dammit!&rdquo; he said.")
+unicode(soup)
+# u'<html><head></head><body>\u201cDammit!\u201d he said.</body></html>'
+
+
+

문서를 문자열로 변환하면, 유니코드 문자들은 UTF-8로 인코드된다. HTML 개체는 다시 복구할 수 없다:

+
str(soup)
+# '<html><head></head><body>\xe2\x80\x9cDammit!\xe2\x80\x9d he said.</body></html>'
+
+
+

기본 값으로, 출력에서 피신 처리가 되는 유일한 문자들은 앰퍼센드와 옆꺽쇠 문자들이다. 이런 문자들은 “&amp;”, “&lt;”, 그리고 “&gt;”로 변환된다. 그래서 뷰티플수프는 무효한 HTML이나 XML을 생성하는 실수를 하지 않게 된다:

+
soup = BeautifulSoup("<p>The law firm of Dewey, Cheatem, & Howe</p>")
+soup.p
+# <p>The law firm of Dewey, Cheatem, &amp; Howe</p>
+
+soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
+soup.a
+# <a href="http://example.com/?foo=val1&amp;bar=val2">A link</a>
+
+
+

이 행위를 바꾸려면 formatter 인자용 값을 prettify(), encode(), 또는 decode()에 제공하면 된다. + +뷰티플수프는 formatter에 대하여 가능한 네 가지 값을 인지한다.

+

기본값은 formatter="minimal"이다. 문자열은 뷰티플수프가 유효한 HTML/XML을 생산한다고 확신할 만큼 처리된다:

+
french = "<p>Il a dit &lt;&lt;Sacr&eacute; bleu!&gt;&gt;</p>"
+soup = BeautifulSoup(french)
+print(soup.prettify(formatter="minimal"))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit &lt;&lt;Sacré bleu!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

+formatter="html"을 건네면, 뷰티플수프는 유니코드 문자를 가능한한 HTML 개체로 변환한다:

+
print(soup.prettify(formatter="html"))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit &lt;&lt;Sacr&eacute; bleu!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

formatter=None을 건네면, 뷰티플수프는 출력시 전혀 문자열을 건드리지 않는다. 이것이 가장 빠른 선택이지만, 다음 예제에서와 같이 잘못해서 뷰티플수프가 무효한 HTML/XML을 생산할 가능성이 있다:

+
print(soup.prettify(formatter=None))
+# <html>
+#  <body>
+#   <p>
+#    Il a dit <<Sacré bleu!>>
+#   </p>
+#  </body>
+# </html>
+
+link_soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
+print(link_soup.a.encode(formatter=None))
+# <a href="http://example.com/?foo=val1&bar=val2">A link</a>
+
+
+

+마지막으로, formatter에 함수를 건네면, 뷰티플수프는 문서에서 문자열과 속성 값에 대하여 하나하나 그 함수를 한 번 호출한다. 이 함수에서 무엇이든 할 수 있다. 다음은 문자열을 대문자로 바꾸고 다른 일은 절대로 하지 않는 포맷터이다:

+
def uppercase(str):
+    return str.upper()
+
+print(soup.prettify(formatter=uppercase))
+# <html>
+#  <body>
+#   <p>
+#    IL A DIT <<SACRÉ BLEU!>>
+#   </p>
+#  </body>
+# </html>
+
+print(link_soup.a.prettify(formatter=uppercase))
+# <a href="HTTP://EXAMPLE.COM/?FOO=VAL1&BAR=VAL2">
+#  A LINK
+# </a>
+
+
+

따로 함수를 작성하고 있다면, bs4.dammit 모듈에 있는 EntitySubstitution 클래스에 관하여 알아야 한다. 이 클래스는 뷰티플수프의 표준 포맷터를 클래스 메쏘드로 구현한다: +“html”포맷터는 EntitySubstitution.substitute_html이고, “minimal” 포맷터는 EntitySubstitution.substitute_xml이다. 이 함수들을 사용하면 formatter=html나 +formatter==minimal를 흉내낼 수 있지만, 더 처리해야할 일이 있다.

+

다음은 가능하면 유니코드 문자를 HTML 개체로 교체하는 예제이다. 그러나 또한 모든 문자열을 대문자로 바꾼다:

+
from bs4.dammit import EntitySubstitution
+def uppercase_and_substitute_html_entities(str):
+    return EntitySubstitution.substitute_html(str.upper())
+
+print(soup.prettify(formatter=uppercase_and_substitute_html_entities))
+# <html>
+#  <body>
+#   <p>
+#    IL A DIT &lt;&lt;SACR&Eacute; BLEU!&gt;&gt;
+#   </p>
+#  </body>
+# </html>
+
+
+

마지막 단점: CData 객체를 만들면, 그 객체 안의 텍스트는 언제나 포맷팅 없이도, 정확하게 똑같이 나타난다. 문서에서 문자열 같은 것들을 세는 메쏘드를 손수 만들 경우, 뷰티플수프는 포맷터 메쏘드를 호출한다. 그러나 반환 값은 무시된다.

+
+
from bs4.element import CData +soup = BeautifulSoup(“<a></a>”) +soup.a.string = CData(“one < three”) +print(soup.a.prettify(formatter=”xml”)) +# <a> +# <![CDATA[one < three]]> +# </a>
+
+
+

get_text()

+

문서나 태그에서 텍스트 부분만 추출하고 싶다면, get_text() 메쏘드를 사용할 수 있다. 이 메쏘드는 문서나 태그 아래의 텍스트를, 유니코드 문자열 하나로 모두 돌려준다:

+
markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
+soup = BeautifulSoup(markup)
+
+soup.get_text()
+u'\nI linked to example.com\n'
+soup.i.get_text()
+u'example.com'
+
+
+

텍스트를 합칠 때 사용될 문자열을 지정해 줄 수 있다:

+
# soup.get_text("|")
+u'\nI linked to |example.com|\n'
+
+
+

뷰티플수프에게 각 테스트의 앞과 뒤에 있는 공백을 걷어내라고 알려줄 수 있다:

+
# soup.get_text("|", strip=True)
+u'I linked to|example.com'
+
+
+

그러나 이 시점에서 대신에 .stripped_strings 발생자를 사용해서, 텍스트를 손수 처리하고 싶을 수 있겠다:

+
[text for text in soup.stripped_strings]
+# [u'I linked to', u'example.com']
+
+
+
+
+
+

사용할 해석기 지정하기

+

단지 HTML만 해석하고 싶을 경우, 조판을 BeautifulSoup 구성자에 넣기만 하면, 아마도 잘 처리될 것이다. 뷰티플수프는 해석기를 여러분 대신 선택해 데이터를 해석한다. 그러나 어느 해석기를 사용할지 바꾸기 위해 구성자에 건넬 수 있는 인자가 몇 가지 더 있다.

+

BeautifulSoup 구성자에 건네는 첫 번째 인자는 문자열이나 열린 파일핸들-즉 해석하기를 원하는 조판이 첫 번째 인자이다. 두 번째 인자는 그 조판이 어떻게 해석되기를 바라는지 지정한다.

+

아무것도 지정하지 않으면, 설치된 해석기중 최적의 HTML 해석기가 배당된다. 뷰티플수프는 lxml 해석기를 최선으로 취급하고, 다음에 html5lib 해석기, 그 다음이 파이썬의 내장 해석기를 선택한다. 이것은 다음 중 하나로 덮어쓸 수 있다:

+
    +
  • 해석하고 싶은 조판의 종류. 현재 “html”, “xml”, 그리고 “html5”가 지원된다.
  • +
  • 사용하고 싶은 해석기의 이름. 현재 선택은 “lxml”, “html5lib”, 그리고 “html.parser” (파이썬의 내장 HTML 해석기)이다.
  • +
+

해석기 설치하기 섹션에 지원 해석기들을 비교해 놓았다.

+

적절한 해석기가 설치되어 있지 않다면, 뷰티플수프는 여러분의 요구를 무시하고 다른 해석기를 선택한다. 지금 유일하게 지원되는 XML 해석기는 lxml이다. lxml 해석기가 설치되어 있지 않으면, XML 해석기를 요구할 경우 아무것도 얻을 수 없고, “lxml”을 요구하더라도 얻을 수 없다.

+
+

해석기 사이의 차이점들

+

뷰티플수프는 다양한 해석기에 대하여 인터페이스가 같다. 그러나 각 해석기는 다르다. 해석기마다 같은 문서에서 다른 해석 트리를 만들어낸다. 가장 큰 차이점은 HTML 해석기와 XML 해석기 사이에 있다. 다음은 HTML로 해석된 짧은 문서이다:

+
BeautifulSoup("<a><b /></a>")
+# <html><head></head><body><a><b></b></a></body></html>
+
+
+

빈 <b /> 태그는 유효한 HTML이 아니므로, 해석기는 그것을 <b></b> 태그 쌍으로 변환한다.

+

다음 똑같은 문서를 XML로 해석한 것이다 (이를 실행하려면 lxml이 설치되어 있어야 한다). 빈 <b /> 태그가 홀로 남았음에 유의하자. 그리고 <html> 태그를 출력하는 대신에 XML 선언이 주어졌음을 주목하자:

+
BeautifulSoup("<a><b /></a>", "xml")
+# <?xml version="1.0" encoding="utf-8"?>
+# <a><b /></a>
+
+
+

+HTML 해석기 사이에서도 차이가 있다. 뷰티플수프에 완벽하게 모양을 갖춘 HTML 문서를 주면, 이 차이는 문제가 되지 않는다. 비록 해석기마다 속도에 차이가 있기는 하지만, 모두 원래의 HTML 문서와 정확하게 똑같이 보이는 데이터 구조를 돌려준다.

+

그러나 문서가 불완전하게 모양을 갖추었다면, 해석기마다 결과가 다르다. 다음은 짧은 무효한 문서를 lxml의 HTML 해석기로 해석한 것이다. 나홀로 </p> 태그는 그냥 무시된다:

+
BeautifulSoup("<a></p>", "lxml")
+# <html><body><a></a></body></html>
+
+
+

다음은 같은 문서를 html5lib로 해석하였다:

+
BeautifulSoup("<a></p>", "html5lib")
+# <html><head></head><body><a><p></p></a></body></html>
+
+
+

나홀로 </p> 태그를 무시하는 대신에, html5lib는 여는 <p> 태그로 짝을 맞추어 준다. 이 해석기는 또한 빈 <head> 태그를 문서에 추가한다.

+

다음은 같은 문서를 파이썬 내장 HTML 해석기로 해석한 것이다:

+
BeautifulSoup("<a></p>", "html.parser")
+# <a></a>
+
+
+

html5lib처럼, 이 해석기는 닫는 </p> 태그를 무시한다. html5lib와 다르게, 이 해석기는 <body> 태그를 추가해서 모양을 갖춘 HTML 문서를 생성하려고 아무 시도도 하지 않는다. lxml과 다르게, 심지어 <html> 태그를 추가하는 것에도 신경쓰지 않는다.

+

문서 “<a></p>”는 무효하므로, 이 테크닉중 어느 것도 “올바른” 처리 방법이 아니다. html5lib 해석기는 HTML5 표준에 있는 테크닉을 사용하므로, 아무래도 “가장 올바른” 방법이라고 주장할 수 있지만, 세 가지 테크닉 모두 같은 주장을 할 수 있다.

+

해석기 사이의 차이점 때문에 스크립트가 영향을 받을 수 있다. 스크립트를 다른 사람들에게 나누어 줄 계획이 있다면, 또는 여러 머신에서 실행할 생각이라면, BeautifulSoup 구성자에 해석기를 지정해 주는 편이 좋다. 그렇게 해야 여러분이 해석한 방식과 다르게 사용자가 문서를 해석할 위험성이 감소한다.

+
+
+
+

인코딩

+

HTML이든 XML이든 문서는 ASCII나 UTF-8 같은 특정한 인코딩으로 작성된다. 그러나 문서를 뷰티플수프에 적재하면, 문서가 유니코드로 변환되었음을 알게 될 것이다:

+
markup = "<h1>Sacr\xc3\xa9 bleu!</h1>"
+soup = BeautifulSoup(markup)
+soup.h1
+# <h1>Sacré bleu!</h1>
+soup.h1.string
+# u'Sacr\xe9 bleu!'
+
+
+

마법이 아니다(확실히 좋은 것이다.). 뷰티플수프는 Unicode, Dammit라는 하위 라이브러리를 사용하여 문서의 인코딩을 탐지하고 유니코드로 변환한다. 자동 인코딩 탐지는 BeautifulSoup 객체의 .original_encoding 속성으로 얻을 수 있다:

+
soup.original_encoding
+'utf-8'
+
+
+

Unicode, Dammit은 대부분 올바르게 추측하지만, 가끔은 실수가 있다. 가끔 올바르게 추측하지만, 문서를 바이트 하나 하나 오랫동안 탐색한 후에야 그렇다. 혹시 문서의 인코딩을 미리 안다면, 그 인코딩을 BeautifulSoup 구성자에 from_encoding로 건네면 실수를 피하고 시간을 절약할 수 있다.

+

다음은 ISO-8859-8로 작성된 문서이다. 이 문서는 Unicode, Dammit이 충분히 살펴보기에는 너무 짧아서, ISO-8859-7로 잘못 인식한다:

+
markup = b"<h1>\xed\xe5\xec\xf9</h1>"
+soup = BeautifulSoup(markup)
+soup.h1
+<h1>νεμω</h1>
+soup.original_encoding
+'ISO-8859-7'
+
+

이를 해결하려면 올바른 from_encoding을 건네면 된다:

+
soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
+soup.h1
+<h1>םולש</h1>
+soup.original_encoding
+'iso8859-8'
+
+

아주 드물게 (보통 UTF-8 문서 안에 텍스트가 완전히 다른 인코딩으로 작성되어 있을 경우), 유일하게 유니코드를 얻는 방법은 몇 가지 문자를 특별한 유니코드 문자 “REPLACEMENT CHARACTER” (U+FFFD, �)로 교체하는 것이다 . Unicode, Dammit이 이를 필요로 하면, UnicodeDammit이나 BeautifulSoup 객체에 대하여 .contains_replacement_characters 속성에 True를 설정할 것이다. +이렇게 하면 유니코드 표현이 원래의 정확한 표현이 아니라는 사실을 알 수 있다. 약간 데이터가 손실된다. 문서에 �가 있지만, .contains_replacement_charactersFalse라면, 원래부터 거기에 있었고 데이터 손실을 감내하지 않는다는 사실을 알게 될 것이다.

+
+

출력 인코딩

+

뷰티플수프로 문서를 작성할 때, UTF-8 문서를 얻는다. 그 문서가 처음에는 UTF-8이 아니었다고 할지라도 말이다. 다음은 Latin-1 인코딩으로 작성된 문서이다:

+
markup = b'''
+ <html>
+  <head>
+   <meta content="text/html; charset=ISO-Latin-1" http-equiv="Content-type" />
+  </head>
+  <body>
+   <p>Sacr\xe9 bleu!</p>
+  </body>
+ </html>
+'''
+
+soup = BeautifulSoup(markup)
+print(soup.prettify())
+# <html>
+#  <head>
+#   <meta content="text/html; charset=utf-8" http-equiv="Content-type" />
+#  </head>
+#  <body>
+#   <p>
+#    Sacré bleu!
+#   </p>
+#  </body>
+# </html>
+
+
+

+<meta> 태그가 재작성되어 문서가 이제 UTF-8이라는 사실을 반영하고 있음을 주목하자.

+

UTF-8이 싫으면, 인코딩을 prettify()에 건넬 수 있다:

+
print(soup.prettify("latin-1"))
+# <html>
+#  <head>
+#   <meta content="text/html; charset=latin-1" http-equiv="Content-type" />
+# ...
+
+
+

또 encode()를 BeautifulSoup 객체, 또는 수프의 다른 어떤 요소에라도 호출할 수 있다. 마치 파이썬 문자열처럼 말이다:

+
soup.p.encode("latin-1")
+# '<p>Sacr\xe9 bleu!</p>'
+
+soup.p.encode("utf-8")
+# '<p>Sacr\xc3\xa9 bleu!</p>'
+
+
+

선택한 인코딩에서 표현이 불가능한 문자는 숫자의 XML 개체 참조로 변환된다. 다음은 유니코드 문자 SNOWMAN이 포함된 문자이다:

+
markup = u"<b>\N{SNOWMAN}</b>"
+snowman_soup = BeautifulSoup(markup)
+tag = snowman_soup.b
+
+
+

눈사람 문자는 UTF-8 문서에 포함될 수 있지만 (☃처럼 생김), ISO-Latin-1이나 ASCII에 그 문자에 대한 표현이 없다. 그래서 “&#9731”으로 변환된다:

+
print(tag.encode("utf-8"))
+# <b>☃</b>
+
+print tag.encode("latin-1")
+# <b>&#9731;</b>
+
+print tag.encode("ascii")
+# <b>&#9731;</b>
+
+
+
+
+

이런, 유니코드군

+

뷰티플수프를 사용하지 않더라도 유니코드를 사용할 수 있다. 인코딩을 알 수 없는 데이터가 있을 때마다 그냥 유니코드가 되어 주었으면 하고 바라기만 하면 된다:

+
from bs4 import UnicodeDammit
+dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!")
+print(dammit.unicode_markup)
+# Sacré bleu!
+dammit.original_encoding
+# 'utf-8'
+
+
+

+유니코드에 더 많은 데이터를 줄 수록, Dammit은 더 정확하게 추측할 것이다. 나름대로 어떤 인코딩일지 짐작이 간다면, 그것들을 리스트로 건넬 수 있다:

+
dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"])
+print(dammit.unicode_markup)
+# Sacré bleu!
+dammit.original_encoding
+# 'latin-1'
+
+
+

Unicode, Dammit는 뷰티플수프가 사용하지 않는 특별한 특징이 두 가지 있다.

+
+

지능형 따옴표

+

Unicode, Dammit을 사용하여 마이크로소프트 지능형 따옴표를 HTML이나 XML 개체로 변환할 수 있다:

+
markup = b"<p>I just \x93love\x94 Microsoft Word\x92s smart quotes</p>"
+
+UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup
+# u'<p>I just &ldquo;love&rdquo; Microsoft Word&rsquo;s smart quotes</p>'
+
+UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup
+# u'<p>I just &#x201C;love&#x201D; Microsoft Word&#x2019;s smart quotes</p>'
+
+
+

또 마이크로소프트 지능형 따옴표를 ASCII 따옴표로 변환할 수 있다:

+
UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup
+# u'<p>I just "love" Microsoft Word\'s smart quotes</p>'
+
+
+

모쪼록 이 특징이 쓸모가 있기를 바라지만, 뷰티플수프는 사용하지 않는다. 뷰티플수프는 기본 행위를 선호하는데, 기본적으로 마이크로소프트 지능형 따옴표를 다른 모든 것과 함께 유니코드 문자로 변환한다:

+
UnicodeDammit(markup, ["windows-1252"]).unicode_markup
+# u'<p>I just \u201clove\u201d Microsoft Word\u2019s smart quotes</p>'
+
+
+
+
+

비 일관적인 인코딩

+

어떤 경우 문서 대부분이 UTF-8이지만, 안에 (역시) 마이크로소프트 지능형 따옴표와 같이 Windows-1252 문자가 들어 있는 경우가 있다. 한 웹 사이트에 여러 소스로 부터 데이터가 포함될 경우에 이런 일이 일어날 수 있다. +UnicodeDammit.detwingle()을 사용하여 그런 문서를 순수한 UTF-8 문서로 변환할 수 있다. 다음은 간단한 예이다:

+
snowmen = (u"\N{SNOWMAN}" * 3)
+quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}")
+doc = snowmen.encode("utf8") + quote.encode("windows_1252")
+
+
+

이 문서는 뒤죽박죽이다. 눈사람은 UTF-8인데 따옴표는 Windows-1252이다. 눈사람 아니면 따옴표를 화면에 나타낼 수 있지만, 둘 다 나타낼 수는 없다:

+
print(doc)
+# ☃☃☃�I like snowmen!�
+
+print(doc.decode("windows-1252"))
+# ☃☃☃“I like snowmen!”
+
+
+

문서를 UTF-8로 디코딩하면 UnicodeDecodeError가 일어나고, Windows-1252로 디코딩하면 알 수 없는 글자들이 출력된다. 다행스럽게도, UnicodeDammit.detwingle()는 그 문자열을 순수 UTF-8로 변환해 주므로, 유니코드로 디코드하면 눈사람과 따옴표를 동시에 화면에 보여줄 수 있다:

+
new_doc = UnicodeDammit.detwingle(doc)
+print(new_doc.decode("utf8"))
+# ☃☃☃“I like snowmen!”
+
+
+

UnicodeDammit.detwingle()는 오직 UTF-8에 임베드된 (또는 그 반대일 수도 있지만) Windows-1252을 다루는 법만 아는데, 이것이 가장 일반적인 사례이다.

+

BeautifulSoup이나 UnicodeDammit 구성자에 건네기 전에 먼저 데이터에 UnicodeDammit.detwingle()을 호출하는 법을 반드시 알아야 한다. 뷰티플수프는 문서에 하나의 인코딩만 있다고 간주한다. 그것이 무엇이든 상관없이 말이다. UTF-8과 Windows-1252를 모두 포함한 문서를 건네면, 전체 문서가 Windows-1252라고 생각할 가능성이 높고, 그 문서는 다음 ` ☃☃☃“I like snowmen!”`처럼 보일 것이다.

+

UnicodeDammit.detwingle()은 뷰티플수프 4.1.0에서 새로 추가되었다.

+
+
+
+
+

문서의 일부만을 해석하기

+

뷰티플수프를 사용하여 문서에서 <a> 태그를 살펴보고 싶다고 해보자. 전체 문서를 해석해서 훓어가며 <a> 태그를 찾는 일은 시간 낭비이자 메모리 낭비이다. 처음부터 <a> 태그가 아닌 것들을 무시하는 편이 더 빠를 것이 분명하다. SoupStrainer 클래스는 문서에 어느 부분을 해석할지 고르도록 해준다. 그냥 SoupStrainer를 만들고 그것을 BeautifulSoup 구성자에 parse_only 인자로 건네면 된다.

+

(이 특징은 html5lib 해석기를 사용중이라면 작동하지 않음을 주목하자. html5lib을 사용한다면, 어쨋거나 문서 전체가 해석된다. 이것은 html5lib가 작업하면서 항상 해석 트리를 재정렬하기 때문이다. 문서의 일부가 실제로 해석 트리에 맞지 않을 경우, 충돌을 일으킨다. 혼란을 피하기 위해, 아래의 예제에서 뷰티플수프에게 파이썬의 내장 해석기를 사용하라고 강제하겠다.)

+
+

SoupStrainer

+

SoupStrainer 클래스는 트리 탐색하기의 전형적인 메쏘드와 같은 인자들을 취한다: name, attrs, text, 그리고 **kwargs이 그 인자들이다. 다음은 세 가지 SoupStrainer 객체이다:

+
from bs4 import SoupStrainer
+
+only_a_tags = SoupStrainer("a")
+
+only_tags_with_id_link2 = SoupStrainer(id="link2")
+
+def is_short_string(string):
+    return len(string) < 10
+
+only_short_strings = SoupStrainer(text=is_short_string)
+
+
+

다시 한 번 더“three sisters” 문서로 돌아가 보겠다. 문서를 세 가지 SoupStrainer 객체로 해석하면 어떻게 보이는지 살펴보자:

+
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>
+"""
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify())
+# <a class="sister" href="http://example.com/elsie" id="link1">
+#  Elsie
+# </a>
+# <a class="sister" href="http://example.com/lacie" id="link2">
+#  Lacie
+# </a>
+# <a class="sister" href="http://example.com/tillie" id="link3">
+#  Tillie
+# </a>
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify())
+# <a class="sister" href="http://example.com/lacie" id="link2">
+#  Lacie
+# </a>
+
+print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify())
+# Elsie
+# ,
+# Lacie
+# and
+# Tillie
+# ...
+#
+
+
+

또한 SoupStrainer트리 탐색하기에서 다룬 메쏘드에 건넬 수 있다. 이는 별로 유용하지는 않지만, 그럼에도 언급해 둔다:

+
soup = BeautifulSoup(html_doc)
+soup.find_all(only_short_strings)
+# [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie',
+#  u'\n\n', u'...', u'\n']
+
+
+
+
+
+

문제 해결

+
+

버전 불일치 문제

+
    +
  • SyntaxError: Invalid syntax (다음 ROOT_TAG_NAME = +u'[document]' 줄에서): 코드를 변경하지 않고서, 파이썬 2 버전의 뷰티플수프를 파이썬 3 아래에서 사용하기 때문에 야기된다.
  • +
  • ImportError: No module named HTMLParser - 파이썬 2 버전의 뷰티플수프를 파이썬 3 아래에서 사용하기 때문에 야기된다.
  • +
  • ImportError: No module named html.parser - 파이썬 3 버전의 뷰티플수프를 파이썬 2에서 실행하기 때문에 야기된다.
  • +
  • ImportError: No module named BeautifulSoup - 뷰티플수프 3 코드를 BS3가 설치되어 있지 않은 시스템에서 실행할 때 야기된다. 또는 꾸러미 이름이 bs4로 바뀌었음을 알지 못하고 뷰티플수프 4 코드를 실행하면 야기된다.
  • +
  • ImportError: No module named bs4 - 뷰티플수프 4 코드를 BS4가 설치되어 있지 않은 시스템에서 실행하면 야기된다.
  • +
+
+
+

XML 해석하기

+

기본값으로, 뷰티플수프는 문서를 HTML로 해석한다. 문서를 XML로 해석하려면, “xml”를 두 번째 인자로 BeautifulSoup 구성자에 건네야 한다:

+
soup = BeautifulSoup(markup, "xml")
+
+
+

lxml이 설치되어 있어야 한다.

+
+
+

기타 해석기 문제

+
    +
  • 스크립트가 한 컴퓨터에서는 잘 되는데 다른 컴퓨터에서는 작동하지 않는다면, 아마도 두 컴퓨터가 다른 해석기를 가지고 있기 때문일 것이다. 예를 들어, lxml이 설치된 컴퓨터에서 스크립트를 개발해 놓고, 그것을 html5lib만 설치된 컴퓨터에서 실행하려고 했을 수 있다. 왜 이것이 문제가 되는지는 해석기들 사이의 차이점을 참고하고, BeautifulSoup 구성자에 특정 라이브러리를 지정해서 문제를 해결하자.
  • +
  • HTMLParser.HTMLParseError: malformed start tag or +HTMLParser.HTMLParseError: bad end tag - 파이썬의 내장 HTML 해석기에 처리가 불가능한 문서를 건네면 야기된다. 다른 HTMLParseError도 아마 같은 문제일 것이다. 해결책: +lxml이나 html5lib를 설치하자.
  • +
  • 알고 있는데 문서에서 그 태그를 발견할 수 없다면 (다시 말해, +find_all()[]를 돌려주거나 find()None을 돌려줄 경우), 아마도 파이썬의 내장 HTML 해석기를 사용하고 있을 가능성이 높다. 이 해석기는 가끔 이해하지 못하면 그 태그를 무시하고 지나간다. 해결책: lxml이나 html5lib를 설치하자.
  • +
  • +HTML 태그와 속성은 대소문자를 구별하므로, 세가지 HTML 해석기 모두 태그와 속성 이름을 소문자로 변환한다. 다시 말해, 다음 조판 <TAG></TAG>는 <tag></tag>로 변환된다. 태그와 속성에 대소문자 혼합 또는 대문자를 그대로 유지하고 싶다면, 문서를 XML로 해석할 필요가 있다.
  • +
+
+
+

기타

+
    +
  • KeyError: [attr] - tag['attr']에 접근했는데 해당 태그에 attr 속성이 정의되어 있지 않을 때 야기된다. 가장 흔한 에러는 KeyError: 'href' 그리고 KeyError: +'class'이다. attr이 정의되어 있는지 잘 모르겠다면, 파이썬 사전에 그렇게 하듯이, tag.get('attr')을 사용하자.
  • +
  • UnicodeEncodeError: 'charmap' codec can't encode character +u'\xfoo' in position bar (또는 그냥 기타 다른 UnicodeEncodeError에 관한 모든 것) - 이 에러는 뷰티플수프에 관련된 문제가 아니다 .이 문제는 두 가지 상황에서 출현한다. 첫 째, 유니코드 문자열을 인쇄했는데 콘솔이 표시할 줄 모를 경우가 있다. (파이썬 위키에서 도움을 받자.) 둘째, 파일에 쓰는데 기본 인코딩으로 지원되지 않는 유니코드 문자열을 건넬 경우가 있다. 이런 경우, 가장 쉬운 해결책은 u.encode("utf8")을 지정해서 그 유니코드 문자열을 UTF-8로 명시적으로 인코드하는 것이다.
  • +
+
+
+

수행성능 개선

+

뷰티플수프는 그 밑에 깔린 해석기보다 더 빠를 수는 없다. 응답 시간이 중요하다면, 다시 말해, 시간제로 컴퓨터를 쓰고 있거나 아니면 컴퓨터 시간이 프로그래머 시간보다 더 가치가 있는 다른 이유가 조금이라도 있다면, 그렇다면 뷰티플수프는 잊어 버리고 직접 lxml 위에 작업하는 편이 좋을 것이다.

+

그렇지만, 뷰티플수프의 속도를 높일 수 있는 방법이 있다. 아래에 해석기로 lxml을 사용하고 있지 않다면, 당장 시작해 보기를 조언한다. 뷰티플수프는 html.parser나 html5lib를 사용하는 것보다 lxml을 사용하는 것이 문서를 상당히 더 빠르게 해석한다.

+

cchardet 라이브러리를 설치하면 인코딩 탐지 속도를 상당히 높일 수 있다.

+

가끔 Unicode, Dammit는 바이트별로 파일을 조사해서 인코딩을 탐지할 수 있을 뿐이다. 이 때문에 뷰티플수프가 기어가는 원인이 된다. 본인의 테스트에 의하면 이런 일은 파이썬 2.x 버전대에서만 일어나고, 러시아나 중국어 인코딩을 사용한 문서에 아주 많이 발생했다. 이런 일이 일어나면, cchardet을 설치하거나, 스크립트에 Python 3를 사용하여 문제를 해결할 수 있다. 혹시 문서의 인코딩을 안다면, 그 인코딩을 BeautifulSoup 구성자에 from_encoding로 건네면, 인코딩 탐지를 완전히 건너뛴다.

+

문서의 일부만 해석하기는 문서를 해석하는 시간을 많이 절약해 주지는 못하겠지만, 메모리가 절약되고, 문서를 훨씬 더 빨리 탐색할 수 있을 것이다.

+
+
+
+

뷰티플수프 3

+

뷰티플수프 3는 이전의 구형으로서, 더 이상 활발하게 개발되지 않는다. 현재는 주요 리눅스 배포본에 모두 함께 꾸려넣어진다:

+

$ apt-get install python-beautifulsoup

+

또 PyPi를 통하여 BeautifulSoup 출간되어 있다:

+

$ easy_install BeautifulSoup

+

$ pip install BeautifulSoup

+

+또한 뷰티플수프 3.2.0 압축파일을 내려받을 수 있다.

+

easy_install beautifulsoup이나 easy_install BeautifulSoup을 실행했는데, 코드가 작동하지 않으면, 실수로 뷰티플수프 3을 설치한 것이다. easy_install beautifulsoup4을 실행할 필요가 있다.

+

뷰티플수프 3 문서는 온라인에 보관되어 있다. 모국어가 중국어라면, 뷰티플수프 3 문서 중국어 번역본을 보는 것이 더 쉬울 것이다. 그 다음에 이 문서를 읽고 뷰티플수프 4에서 변한 것들을 알아보자.

+
+

BS4로 코드 이식하기

+

+뷰티플수프 3용 코드는 하나만 살짝 바꾸면 뷰티플수프 4에도 작동한다. 꾸러미 이름을 BeautifulSoup에서 bs4로 바꾸기만 하면 된다. 그래서 다음은:

+
from BeautifulSoup import BeautifulSoup
+
+
+

다음과 같이 된다:

+
from bs4 import BeautifulSoup
+
+
+
    +
  • “No module named BeautifulSoup”와 같이 ImportError를 만난다면, 문제는 뷰티플수프 3 코드를 시도하는데 뷰티플수프 4만 설치되어 있기 때문이다.
  • +
  • “No module named bs4”와 같은 ImportError를 만난다면, 문제는 뷰티플수프 4 코드를 시도하는데 뷰티플수프 3만 설치되어 있기 때문이다.
  • +
+

BS4는 BS3와 대부분 하위 호환성이 있으므로, 대부분의 메쏘드는 폐기되고 PEP 8을 준수하기 위해 새로운 이름이 주어졌다. 이름바꾸기와 변화가 많이 있지만, 그 중에 몇 가지는 하위 호환성이 깨진다.

+

다음은 BS3 코드를 변환해 BS4에 이식하고자 할 때 알아야 할 것들이다:

+
+

해석기가 필요해

+

뷰티플수프 3는 파이썬의 SGMLParser해석기를 사용했다. 이 모듈은 파이썬 3.0에서 제거되었다. 뷰티플수프 4는 기본으로 html.parser을 사용하지만, 대신에 lxml이나 html5lib을 설치해 사용할 수있다. 비교는 해석기 설치하기를 참조하자.

+

+html.parserSGMLParser와 같은 해석기가 아니기 때문에, 무효한 조판을 다르게 취급한다. 보통 “차이점은” 무효한 조판을 다룰 경우 html.parser가 해석기가 충돌을 일으키는 것이다. 이런 경우, 또다른 해석기를 설치할 필요가 있다. 그러나 html.parserSGMLParser와는 다른 해석 트리를 생성한다. 이런 일이 일어나면, BS3 코드를 업데이트하여 새로운 트리를 다루도록 해야 할 필요가 있다.

+
+
+

메쏘드 이름

+
    +
  • renderContents -> encode_contents
  • +
  • replaceWith -> replace_with
  • +
  • replaceWithChildren -> unwrap
  • +
  • findAll -> find_all
  • +
  • findAllNext -> find_all_next
  • +
  • findAllPrevious -> find_all_previous
  • +
  • findNext -> find_next
  • +
  • findNextSibling -> find_next_sibling
  • +
  • findNextSiblings -> find_next_siblings
  • +
  • findParent -> find_parent
  • +
  • findParents -> find_parents
  • +
  • findPrevious -> find_previous
  • +
  • findPreviousSibling -> find_previous_sibling
  • +
  • findPreviousSiblings -> find_previous_siblings
  • +
  • nextSibling -> next_sibling
  • +
  • previousSibling -> previous_sibling
  • +
+

뷰티플수프 구성자에 건네는 인자들 중에서 같은 이유로 이름이 바뀌었다:

+
    +
  • BeautifulSoup(parseOnlyThese=...) -> BeautifulSoup(parse_only=...)
  • +
  • BeautifulSoup(fromEncoding=...) -> BeautifulSoup(from_encoding=...)
  • +
+

파이썬 3와의 호환을 위해 한 가지 메쏘드 이름을 바꾸었다:

+
    +
  • Tag.has_key() -> Tag.has_attr()
  • +
+

더 정확한 용어를 위해 한 속성의 이름을 바꾸었다:

+
    +
  • Tag.isSelfClosing -> Tag.is_empty_element
  • +
+

파이썬에서 특별한 의미가 있는 단어들을 피해서 세 가지 속성의 이름을 바꾸었다. 다른 것들과 다르게 이 변경사항은 하위 호환이 되지 않는다. 이런 속성을 BS3에 사용하면, BS4로 이식할 때 코드가 깨질 것이다.

+
    +
  • UnicodeDammit.unicode -> UnicodeDammit.unicode_markup
  • +
  • Tag.next -> Tag.next_element
  • +
  • Tag.previous -> Tag.previous_element
  • +
+
+
+

발생자

+

발생자에 PEP 8을-준수하는 이름을 부여하고, 특성으로 변환하였다:

+
    +
  • childGenerator() -> children
  • +
  • nextGenerator() -> next_elements
  • +
  • nextSiblingGenerator() -> next_siblings
  • +
  • previousGenerator() -> previous_elements
  • +
  • previousSiblingGenerator() -> previous_siblings
  • +
  • recursiveChildGenerator() -> descendants
  • +
  • parentGenerator() -> parents
  • +
+

그래서 다음과 같이 하는 대신에:

+
for parent in tag.parentGenerator():
+    ...
+
+
+

다음과 같이 작성할 수 있다:

+
for parent in tag.parents:
+    ...
+
+
+

(그러나 구형 코드도 여전히 작동한다.)

+

어떤 발생자들은 일이 끝난후 None을 돌려주곤 했다. 그것은 버그였다. 이제 발생자는 그냥 멈춘다.

+

두 가지 발생자가 새로 추가되었는데, .strings와 .stripped_strings가 그것이다. .strings는 NavigableString 객체를 산출하고, .stripped_strings는 공백이 제거된 파이썬 문자열을 산출한다.

+
+
+

XML

+

이제 XML 해석을 위한 BeautifulStoneSoup 클래스는 더 이상 없다. XML을 해석하려면“xml”을 두번째 인자로 BeautifulSoup 구성자에 건네야 한다. 같은 이유로, BeautifulSoup 구성자는 더 이상 isHTML 인자를 인지하지 못한다.

+

뷰티플수프의 빈-원소 XML 태그 처리 방식이 개선되었다. 전에는 XML을 해석할 때 명시적으로 어느 태그가 빈-원소 태그로 간주되는지 지정해야 했었다. 구성자에 selfClosingTags 인자를 보내 봐야 더 이상 인지하지 못한다. 대신에, +뷰티플수프는 빈 태그를 빈-원소 태그로 간주한다. 빈-원소 태그에 자손을 하나 추가하면, 더 이상 빈-원소 태그가 아니다.

+
+
+

개체

+

+HTML이나 XML 개체가 들어 오면 언제나 그에 상응하는 유니코드 문자로 변환된다. 뷰티플수프 3는 개체들을 다루기 위한 방법이 중첩적으로 많았다. 이제 중복이 제거되었다. BeautifulSoup 구성자는 더 이상 +smartQuotesTo이나 convertEntities 인자를 인지하지 않는다. (Unicode, Dammit은 여전히 smart_quotes_to가 있지만, 그의 기본값은 이제 지능형 따옴표를 유니코드로 변환하는 것이다.) + +HTML_ENTITIES, +XML_ENTITIES, 그리고 XHTML_ENTITIES 상수는 제거되었다. 왜냐하면 이제 더 이상 존재하지 않는 특징을 구성하기 때문이다 (유니코드 문자열을 제대로 모두 변환하지 못했다).

+

유니코드 문자들을 다시 출력시에 HTML 개체로 변환하고 싶다면, 그것들을 UTF-8 문자로 변환하기 보다, 출력 포맷터를 사용할 필요가 있다.

+
+
+

기타

+

Tag.string은 이제 재귀적으로 작동한다. 태그 A에 태그 B만 달랑 있고 다른 것이 없다면, A.string은 B.string과 똑같다. (이전에서는 None이었다.)

+

다중-값 속성class와 같이 문자열이 아니라 문자열 리스트를 그 값으로 가진다. 이 사실은 CSS 클래스로 검색하는 방식에 영향을 미친다.

+

+find* 메쏘드에 text 그리고 name 같은 태그-종속적 인자를 모두 건네면, 뷰티플수프는 태그-종속적 기준에 부합하고 그 태그의 Tag.stringtext 값에 부합하는 태그들을 탐색한다. 문자열 자체는 찾지 않는다. 이전에, 뷰티플수프는 태그-종속적 인자는 무시하고 문자열을 찾았다.

+

+BeautifulSoup 구성자는 더 이상 markupMassage 인자를 인지하지 않는다. 이제 조판을 제대로 처리하는 일은 해석기의 책임이다..

+

ICantBelieveItsBeautifulSoup 그리고 BeautifulSOAP와 같이 거의-사용되지 않는 해석기 클래스는 제거되었다. 이제 애매모호한 조판을 처리하는 방법은 해석기가 결정한다.

+

+prettify() 메쏘드는 이제, bytestring이 아니라 유니코드 문자열을 돌려준다.

+
+
+
+ + +
+
+
+
+
+

목차

+ + +

이 페이지

+ + + +
+
+
+
+ + + + + + + diff --git a/doc.ptbr/source/6.1.jpg b/doc.ptbr/source/6.1.jpg new file mode 100644 index 0000000..97014f0 Binary files /dev/null and b/doc.ptbr/source/6.1.jpg differ diff --git a/doc.ptbr/source/conf.py b/doc.ptbr/source/conf.py new file mode 100644 index 0000000..cd679b5 --- /dev/null +++ b/doc.ptbr/source/conf.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# +# Beautiful Soup documentation build configuration file, created by +# sphinx-quickstart on Thu Jan 26 11:22:55 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Beautiful Soup' +copyright = u'2004-2015, Leonard Richardson' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '4' +# The full version, including alpha/beta/rc tags. +release = '4.4.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'BeautifulSoupdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'BeautifulSoup.tex', u'Beautiful Soup Documentation', + u'Leonard Richardson', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'beautifulsoup', u'Beautiful Soup Documentation', + [u'Leonard Richardson'], 1) +] + + +# -- Options for Epub output --------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = u'Beautiful Soup' +epub_author = u'Leonard Richardson' +epub_publisher = u'Leonard Richardson' +epub_copyright = u'2012, Leonard Richardson' + +# The language of the text. It defaults to the language option +# or en if the language is not set. +#epub_language = '' + +# The scheme of the identifier. Typical schemes are ISBN or URL. +#epub_scheme = '' + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +#epub_identifier = '' + +# A unique identification for the text. +#epub_uid = '' + +# HTML files that should be inserted before the pages created by sphinx. +# The format is a list of tuples containing the path and title. +#epub_pre_files = [] + +# HTML files shat should be inserted after the pages created by sphinx. +# The format is a list of tuples containing the path and title. +#epub_post_files = [] + +# A list of files that should not be packed into the epub file. +#epub_exclude_files = [] + +# The depth of the table of contents in toc.ncx. +#epub_tocdepth = 3 + +# Allow duplicate toc entries. +#epub_tocdup = True diff --git a/doc.ptbr/source/index.rst b/doc.ptbr/source/index.rst new file mode 100644 index 0000000..f596d44 --- /dev/null +++ b/doc.ptbr/source/index.rst @@ -0,0 +1,3261 @@ +Documentação Beautiful Soup +============================ + +.. image:: 6.1.jpg + :align: right + :alt: "O Lacaio-Peixe começou tirando debaixo do braço uma grande carta, quase tão grande quanto ele mesmo." + + +`Beautiful Soup `_ é uma biblioteca +Python de extração de dados de arquivos HTML e XML. Ela funciona com o seu interpretador (parser) favorito +a fim de prover maneiras mais intuitivas de navegar, buscar e modificar uma árvore de análise (parse tree). +Ela geralmente economiza horas ou dias de trabalho de programadores ao redor do mundo. + +Estas instruções ilustram as principais funcionalidades do Beautiful Soup 4 +com exemplos. Mostro para o que a biblioteca é indicada, como funciona, +como se usa e como fazer aquilo que você quer e o que fazer quando ela frustra suas +expectativas. + +Os exemplos nesta documentação devem funcionar da mesma maneira em Python 2.7 e Python 3.2. + +`Você pode estar procurando pela documentação do Beautiful Soup 3 +`_. +Se está, informo que o Beautiful Soup 3 não está mais sendo desenvolvido, +e que o Beautiful Soup 4 é o recomendado para todos os novos projetos. +Se você quiser saber as diferenças entre as versões 3 e 4, veja `Portabilidade de código para BS4`_. + +Esta documentação foi traduzida para outros idiomas pelos usuários do Beautiful Soup: + +* `这篇文档当然还有中文版. `_ +* このページは日本語で利用できます(`外部リンク `_) +* 이 문서는 한국어 번역도 가능합니다. (`외부 링크 `_) +* Este documento também está disponível em Português do Brasil + +Como conseguir ajuda: +--------------------- + +Se você tem perguntas sobre o Beautiful Soup ou está com dificuldades, +`envie uma mensagem para nosso grupo de discussão +`_. Se o seu +problema envolve a interpretação de um documento HTML, não esqueça de mencionar +:ref:`o que a função diagnose() diz ` sobre seu documento. + +Início Rápido +============= + +Este é o HTML que usarei como exemplo ao longo deste documento +É um trecho de "Alice no País das Maravilhas":: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + +Executando o arquivo "three sisters" através do Beautiful Soup, ele nos +retorna um objeto ``BeautifulSoup``, que apresenta o documento como uma estrutura +de dados aninhada:: + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + + print(soup.prettify()) + # + # + # + # The Dormouse's story + # + # + # + #

+ # + # The Dormouse's story + # + #

+ #

+ # Once upon a time there were three little sisters; and their names were + # + # Elsie + # + # , + # + # Lacie + # + # and + # + # Tillie + # + # ; and they lived at the bottom of a well. + #

+ #

+ # ... + #

+ # + # + +Abaixo verificamos algumas maneiras simples de navegar na estrutura:: + + soup.title + # The Dormouse's story + + soup.title.name + # u'title' + + soup.title.string + # u'The Dormouse's story' + + soup.title.parent.name + # u'head' + + soup.p + #

The Dormouse's story

+ + soup.p['class'] + # u'title' + + soup.a + # Elsie + + soup.find_all('a') + # [Elsie, + # Lacie, + # Tillie] + + soup.find(id="link3") + # Tillie + +Uma tarefa comum é extratir todas as URLs encontradas nas tags de uma página:: + + for link in soup.find_all('a'): + print(link.get('href')) + # http://example.com/elsie + # http://example.com/lacie + # http://example.com/tillie + +Outra tarefa comum é extrair todo o texto de uma página:: + + print(soup.get_text()) + # The Dormouse's story + # + # The Dormouse's story + # + # Once upon a time there were three little sisters; and their names were + # Elsie, + # Lacie and + # Tillie; + # and they lived at the bottom of a well. + # + # ... + +Isso se parece com o que você precisa? Então vá em frente! + +Instalando o Beautiful Soup +=========================== + +Se você está usando uma versão recente das distribuições Linux Debian ou Ubuntu, +você pode instalar o Beautiful Soup facilmente utilizando o gerenciador de pacotes + +:kbd:`$ apt-get install python-bs4` (for Python 2) + +:kbd:`$ apt-get install python3-bs4` (for Python 3) + +O Beautiful Soup 4 também está publicado no PyPi. Portanto, se +você não conseguir instalá-lo através de seu gerenciador de pacotes, você +pode fazer isso com ``easy_install`` ou ``pip``. O nome do pacote é ``beautifulsoup4``, +e o mesmo pacote é válido tanto para Python 2 quanto Python 3. Tenha certeza de utilizar +a versão correta de ``pip`` ou ``easy_install`` para sua versão do Python (estarão +nomeados como ``pip3`` ou ``easy_install3`` ,respectivamente, se você estiver usando Python 3). + + +:kbd:`$ easy_install beautifulsoup4` + +:kbd:`$ pip install beautifulsoup4` + +(O pacote ``BeautifulSoup`` provavelmente `não` é o que você quer. Esta +é a versão anterior, `Beautiful Soup 3`_. Muitos softwares utilizam +BS3, por isso ele ainda está disponível, mas se você está criando algo novo, +você deve instalar o ``beautifulsoup4``.) + +Se você não possui o ``easy_install`` ou ``pip`` instalados, você pode fazer +o download através do tarball do arquivo fonte do Beautiful Soup 4 +`_ e +instalar através do ``setup.py``. + +:kbd:`$ python setup.py install` + +Se tudo isso falhar, a licença do Beautiful Soup lhe permite empacotar +toda a biblioteca em sua aplicação. Você pode fazer o download do arquivo +tarball, copiar o diretório ``bs4`` do código-fonte para sua aplicação e +utilizar o Beautiful Soup sem nenhum processo de instalação. + +Eu utilizo Python 2.7 e Python 3.2 para desenvolver o Beautiful Soup, +mas ele também funcionará com outras versões recentes. + +Problemas após a instalação +--------------------------- + +O Beautiful Soup é empacotado em Python 2. Quando você o instala utilizando +Python 3 ele é automaticamente convertido para esta versão. Se você não instalar o pacote, o +código não será convertido. Também foi relatado versões erradas sendo instaladas em +máquinas Windows. + +Se você receber um ``ImportError`` "No module named HTMLParser", seu problema +é que você está utilizando o formato de código Python 2 sob Python 3. + +Se você receber um ``ImportError`` "No module named html.parser", seu problema +é que você está utilizando o formato de código Python 3 sob Python 2. + +Em ambos os casos, sua melhor opção é remover completamente a +instalação do Beautiful Soup do seu sistema (incluindo qualquer diretório +criado quando o tarball foi descompactado) e realizar a instalação novamente. + +Se você receber um ``SyntaxError`` "Invalid syntax" na linha +``ROOT_TAG_NAME = u'[document]'``, você terá que converter o Python 2 +em Python 3. Você pode fazer isso instalando o pacote: + +:kbd:`$ python3 setup.py install` + +ou manualmente executando o script de conversão ``2to3`` no +diretório ``bs4``: + +:kbd:`$ 2to3-3.2 -w bs4` + +.. _parser-installation: + + +Instalando um interpretador (parser) +------------------------------------ + + +O Beautiful Soup não só suporta o parser HTML incluído na biblioteca +padrão do Python como também inúmeros parsers de terceiros. +Um deles é o `parser lxml `_. Dependendo de sua configuração, +você podera instalar o lxml com algum dos seguintes comandos: + +:kbd:`$ apt-get install python-lxml` + +:kbd:`$ easy_install lxml` + +:kbd:`$ pip install lxml` + +Outra alternativa é o parser `html5lib +`_ do Python puro, o qual analisa o HTML +da mesma maneira que o navegador o faz. Dependendo de sua configuração, +você podera instalar o html5lib com algum dos seguintes comandos: + +:kbd:`$ apt-get install python-html5lib` + +:kbd:`$ easy_install html5lib` + +:kbd:`$ pip install html5lib` + +Esta tabela resume as vantagens e desvantagens de cada parser:- + ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ +| Parser | Uso Padrão | Vantagens | Desvantagens | ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ +| html.parser (puro) | ``BeautifulSoup(markup, "html.parser")`` | * Baterias inclusas | * Não tão rápido quanto | +| | | * Velocidade Decente | lxml, menos leniente | +| | | * Leniente (Python 2.7.3 | que html5lib. | +| | | e 3.2.) | | ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ +| HTML (lxml) | ``BeautifulSoup(markup, "lxml")`` | * Muito rápido | * Dependencia externa de | +| | | * Leniente | C | ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ +| XML (lxml) | ``BeautifulSoup(markup, "lxml-xml")`` | * Muito rápido | * Dependência externa de | +| | ``BeautifulSoup(markup, "xml")`` | * O único parser XML atualmente| C | +| | | suportado | | ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ +| html5lib | ``BeautifulSoup(markup, "html5lib")`` | * Extremamente leniente | * Muito lento | +| | | * Analisa as páginas da mesma | * Dependência externa de | +| | | maneira que o navegador o faz| Python | +| | | * Cria HTML5 válidos | | ++----------------------+--------------------------------------------+--------------------------------+--------------------------+ + +Se for possível recomendo que você instale e utilize o lxml pelo desempenho. +Se você está utilizando o Python 2 anterior a 2.7.3 ou uma versão do Python 3 +anterior a 3.2.2, é `essencial` que você instale o lxml ou o html5lib. O parser +HTML nativo do Python não é muito bom para versões mais antigas. + +Note que se um documento é inválido, diferentes parsers irão gerar +diferentes árvores BeautifulSoup para isso. Veja :ref:`Diferenças entre os interpretadores (parsers)` +para detalhes. + + +Criando a "Sopa" +================ + +Para analisar um documento, passe-o como argumento dentro de um construtor ``BeautifulSoup``. +Você pode passar este argumento como uma string ou manipulador da função open():: + + from bs4 import BeautifulSoup + + with open("index.html") as fp: + soup = BeautifulSoup(fp) + + soup = BeautifulSoup("data") + +Primeiro, o documento é convertido para Unicode e as entidades HTML +são convertidas para caracteres Unicode:: + + BeautifulSoup("Sacré bleu!") + Sacré bleu! + +O Beautiful Soup então interpreta o documento usando o melhor parser disponível. +Ele irá utilizar um parser HTML ao menos que você indique a ele que utilize um +parser XML.(Veja `Interpretando XML`_.) + +Tipos de objetos +================ + +O Beautiful Soup transforma um documento HTML complexo em uma complexa árvore de objetos Python. +Mas você terá apenas que lidar com quatro `tipos` de objetos: ``Tag``, ``NavigableString``, ``BeautifulSoup``, +e ``Comment``. + +.. _Tag: + +``Tag`` +------- + +Um objeto ``Tag`` corresponde a uma tag XML ou HTML do documento original:: + + soup = BeautifulSoup('Extremely bold') + tag = soup.b + type(tag) + # + +As tags possuem muitos atributos e métodos que eu falarei mais sobre em +`Navegando pela árvore`_ e `Buscando na árvore`_. Por agora, as características +mais importantes da tag são seu nome e atributos. + +Nome +^^^^ + +Toda tag possui um nome, acessível através de ``.name``:: + + tag.name + # u'b' + +Se você mudar o nome de uma tag, a alteração será refletida em qualquer HTML gerado pelo +Beautiful Soup:: + + tag.name = "blockquote" + tag + #
Extremely bold
+ +Atributos +^^^^^^^^^^ +Uma tag pode ter inúmeros atributos. A tag ```` +possui um atributo "id" que possui o valor "boldest". Você pode +acessar um atributo de uma tag tratando-a como um dicionário:: + + tag['id'] + # u'boldest' + +Você pode acessar este dicionário diretamente através de ``.attrs``:: + + tag.attrs + # {u'id': 'boldest'} + +Você pode adicionar, remover ou modificar os atributos de uma tag. Novamente, isso pode +ser feito tratando a tag como um dicionário:: + + tag['id'] = 'verybold' + tag['another-attribute'] = 1 + tag + # + + del tag['id'] + del tag['another-attribute'] + tag + # + + tag['id'] + # KeyError: 'id' + print(tag.get('id')) + # None + +.. _multivalue: + +Atributos com múltiplos valores +&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& + +O HTML 4 define alguns atributos que podem ter múltiplos valores. O HTML 5 +removeu alguns deles, mas definiu alguns novos. O atributo mais comum +que pode receber múltiplos valores é o ``class`` (ou seja, a tag pode ter mais de uma classe CSS). +Outros são ``rel``, ``rev``, ``accept-charset``, ``headers``, e ``accesskey``. +O Beautiful Soup apresenta o(s) valor(es) de um atributo deste tipo como uma lista:: + + css_soup = BeautifulSoup('

') + css_soup.p['class'] + # ["body"] + + css_soup = BeautifulSoup('

') + css_soup.p['class'] + # ["body", "strikeout"] + +Se um atributo possui mais de um valor, mas não é um atributo +que aceita múltiplos valores conforme definido por qualquer versão do +padrão HTML, o Beautiful Soup retornará como um valor único:: + + id_soup = BeautifulSoup('

') + id_soup.p['id'] + # 'my id' + +Quando a tag é transformada novamente em string, os valores do atributo múltiplo +são consolidados:: + + rel_soup = BeautifulSoup('

Back to the homepage

') + rel_soup.a['rel'] + # ['index'] + rel_soup.a['rel'] = ['index', 'contents'] + print(rel_soup.p) + #

Back to the homepage

+ +Você pode desabilitar esta opção passando ``multi_valued_attributes=None`` como argumento +dentro do construtor ``BeautifulSoup`` :: + + no_list_soup = BeautifulSoup('

', 'html', multi_valued_attributes=None) + no_list_soup.p['class'] + # u'body strikeout' + +Você pode utilizar ```get_attribute_list`` para retornar um valor no formato de lista, seja um atributo de +múltiplos valores ou não:: + + id_soup.p.get_attribute_list('id') + # ["my id"] + +Se você analisar um documento como XML, nenhum atributo será tratado como de múltiplos valores:: + + xml_soup = BeautifulSoup('

', 'xml') + xml_soup.p['class'] + # u'body strikeout' + +Novamente, você pode configurar isto usando o argumento ``multi_valued_attributes``:: + + class_is_multi= { '*' : 'class'} + xml_soup = BeautifulSoup('

', 'xml', multi_valued_attributes=class_is_multi) + xml_soup.p['class'] + # [u'body', u'strikeout'] + +Você provavelmente não precisará fazer isso, mas se fizer, use os padrões como guia. +Eles implementam as regras descritas na especificação do HTML:: + + from bs4.builder import builder_registry + builder_registry.lookup('html').DEFAULT_CDATA_LIST_ATTRIBUTES + + +``NavigableString`` +------------------- + +Uma string corresponde a um texto dentro de uma tag. +O Beautiful Soup usa a classe ``NavigableString`` para armazenar este texto:: + + tag.string + # u'Extremely bold' + type(tag.string) + # + +Uma ``NavigableString`` é como uma string Unicode do Python, exceto +que ela também suporta algumas características descritas em `Navegando pela árvore`_ +e `Buscando na árvore`_. Você pode converter um +``NavigableString`` em uma string Unicode utilizando ``unicode()``:: + + unicode_string = unicode(tag.string) + unicode_string + # u'Extremely bold' + type(unicode_string) + # + +Você não pode editar uma string "in place", mas você pode substituir +uma string por outra usando :ref:`replace_with()`:: + + tag.string.replace_with("No longer bold") + tag + #
No longer bold
+ +``NavigableString`` suporta a maior parte das características descritas em +`Navegando pela árvore`_ e `Buscando na árvore`_, mas não todas elas. +Em particular, desde que uma string não pode conter de tudo (da maneira que +uma tag pode conter uma string ou outra tag), as strings não suportam os +atributos ``.contents`` ou ``.string`` ou o método ``find()``. + +Se você quer utilizar uma ``NavigableString`` fora do Beautiful Soup, +você deve chamar o ``unicode()`` para transformá-la em uma string Unicode Python +padrão. Se você não fizer isso, sua string irá carregar uma referência de toda sua +árvore Beautiful Soup, mesmo que você já não esteja mais usando ela, o que é um grande +desperdício de memória. + +``BeautifulSoup`` +----------------- + +O objeto ``BeautifulSoup`` em si representa o documento como um todo. +Para maioria dos propósitos, você pode tratá-lo como um objeto :ref:`Tag`. +Isso significa que irá suportar a maioria dos métodos descritos em +`Navegando pela árvore`_ e `Buscando na árvore`_. + +Sabendo que o objeto ``BeautifulSoup`` não corresponde a uma tag +HTML ou XML propriamente dita, ele não tem nome e nem atributos. Mas em alguns +casos é útil observar seu ``.name``; então, foi dado o especial +``.name`` "[document]":: + + soup.name + # u'[document]' + +Comentários e outras strings especiais +-------------------------------------- + +``Tag``, ``NavigableString``, e ``BeautifulSoup`` abrangem quase +tudo o que você encontrará em um arquivo HTML ou XML, mas há alguns +pontos faltando. O único deles que você provavelmente precisará se preocupar +é o comentário:: + + markup = "" + soup = BeautifulSoup(markup) + comment = soup.b.string + type(comment) + # + +O objeto ``Comment`` é apenas um tipo especial de ``NavigableString``:: + + comment + # u'Hey, buddy. Want to buy a used parser' + +Mas quando aparece como parte de um documento HTML, um ``Comment`` é +exibido com uma formatação especial:: + + print(soup.b.prettify()) + # + # + # + +O Beautiful Soup define classes para qualquer outra coisa que possa +aparecer em um documento XML: ``CData``, ``ProcessingInstruction``, +``Declaration`` e ``Doctype``. Assim como ``Comment``, estas classes +são subclasses de ``NavigableString`` que adicionam algo a string. +Aqui está um exemplo que substitui o comentário por um bloco CDATA:: + + from bs4 import CData + cdata = CData("A CDATA block") + comment.replace_with(cdata) + + print(soup.b.prettify()) + # + # + # + + +Navegando pela árvore +===================== + +Aqui está o documento HTML "Three sisters" novamente:: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + +Eu usarei este documento como exemplo para mostrar como navegar +de uma parte para outra do documento. + +Descendo na Árvore +------------------ +As tags podem conter strings e outras tags. Estes elementos são as tags +`filhas` (children). O Beautiful Soup oferece diferentes atributos para +navegar e iterar sobre as tags filhas. + +Note que as strings Beautiful Soup não suportam qualquer destes atributos, +porque uma string não pode ter filhos. + +Navegar usando os nomes das tags +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +A maneira mais simples de navegar pela árvore é utilizar +o nome da tag que você quer. Se você quer a tag , +simplesmente use ``soup.head``:: + + soup.head + # The Dormouse's story + + soup.title + # The Dormouse's story + +Você pode usar este truque de novo, e de novo, para focar em certa parte da +árvore de análise. Este código retorna a primeira tag abaixo da tag :: + + soup.body.b + # The Dormouse's story + +Utilizando o nome da tag como atributo irá lhe retornar apenas a `primeira` +tag com aquele nome:: + + soup.a + # Elsie + +Se você precisar retornar `todas` as tags , ou algo mais complicado +que a primeira tag com um certo nome, você precisará utilizar um dos +métodos descritos em `Buscando na árvore`_, como `find_all()`:: + + soup.find_all('a') + # [Elsie, + # Lacie, + # Tillie] + +``.contents`` e ``.children`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +As tags filhas de uma outra tag estão disponíveis em uma lista chamada por ``.contents``:: + + head_tag = soup.head + head_tag + # The Dormouse's story + + head_tag.contents + [The Dormouse's story] + + title_tag = head_tag.contents[0] + title_tag + # The Dormouse's story + title_tag.contents + # [u'The Dormouse's story'] + +O objeto ``BeautifulSoup`` em si possui filhos. Neste caso, a tag + é a filha do objeto ``BeautifulSoup``.:: + + len(soup.contents) + # 1 + soup.contents[0].name + # u'html' + +Uma string não possui o atributo ``.contents``, porque ela não pode conter +nada:: + + text = title_tag.contents[0] + text.contents + # AttributeError: 'NavigableString' object has no attribute 'contents' + +Ao invés de retorná-las como uma lista, você pode iterar sobre as +tag's filhas usando o gerador ``.children``:: + + for child in title_tag.children: + print(child) + # The Dormouse's story + +``.descendants`` +^^^^^^^^^^^^^^^^ + +Os atributos ``.contents`` e ``.children`` somente consideram tags que +são `filhas diretas`. Por instância, a tag tem apenas uma tag filha direta, +a tag :: + + head_tag.contents + # [<title>The Dormouse's story] + +Mas a tag em si possui uma filha: a string "The Dormouse's story". +Existe uma percepção de que esta string também é filha da tag <head>. +O atributo ``.descendants`` permite que você itere sobre `todas` +as tags filhas, recursivamente: suas filhas diretas, as filhas de suas filhas, e assim por diante:: + + for child in head_tag.descendants: + print(child) + # <title>The Dormouse's story + # The Dormouse's story + +A tag possui apenas uma filha, mas também possui dois `descentendes`: +a tag e a filha da tag <title>. O objeto ``BeautifulSoup`` possui apenas +uma filha direta (a tag <html>), mas ele possui vários descendentes:: + + len(list(soup.children)) + # 1 + len(list(soup.descendants)) + # 25 + +.. _.string: + +``.string`` +^^^^^^^^^^^ + +Se uma tag possui apenas uma filha, e esta filha é uma ``NavigableString``, +esta filha pode ser disponibilizada através de ``.string``:: + + title_tag.string + # u'The Dormouse's story' + +Se a filha única de uma tag é outra tag e esta tag possui uma +``.string``, então considera-se que a tag mãe tenha a mesma +``.string`` como sua filha:: + + head_tag.contents + # [<title>The Dormouse's story] + + head_tag.string + # u'The Dormouse's story' + +Se uma tag contém mais de uma coisa, então não fica claro a que +``.string`` deve se referir, portanto ``.string`` será definida como +``None``:: + + print(soup.html.string) + # None + +.. _string-generators: + +``.strings`` e ``stripped_strings`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Se existe mais de alguma coisa dentro da tag, você pode continuar +olhando apenas as strings. Use o gerador ``.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' + +Estas strings tendem a ter muitos espaços em branco, os quais você +pode remover utilizando o gerador ``.stripped_strings`` como alternativa:: + + 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'...' + +Aqui, strings formadas inteiramente por espaços em branco serão ignoradas, +e espaços em branco no início e no fim das strings serão removidos. + +Subindo na Árvore +----------------- + +Continuando a analogia da árvore como "família", toda tag e toda string possuem +`tags mães (parents)`: a tag que as contém. + +.. _.parent: + +``.parent`` +^^^^^^^^^^^ + +Você pode acessar o elemento mãe com o atributo ``.parent``. No +exemplo "three sisters", a tag é mãe da tag :: + + title_tag = soup.title + title_tag + # <title>The Dormouse's story + title_tag.parent + # The Dormouse's story + +A string de title tem uma mãe: a tag que a contém:: + + title_tag.string.parent + # <title>The Dormouse's story + +A tag mãe de todo documento () é um objeto ``BeautifulSoup`` em si:: + + html_tag = soup.html + type(html_tag.parent) + # + +E o ``.parent`` de um objeto ``BeautifulSoup`` é definido como None:: + + print(soup.parent) + # None + +.. _.parents: + +``.parents`` +^^^^^^^^^^^^ +Você pode iterar sobre todos os elementos pais com +``.parents``. Este exemplo usa ``.parents`` para viajar de uma tag +profunda no documento, para o elemento mais ao topo da árvore do documento:: + + link = soup.a + link + # Elsie + for parent in link.parents: + if parent is None: + print(parent) + else: + print(parent.name) + # p + # body + # html + # [document] + # None + +Navegando para os lados: +------------------------ + +Considere um simples documento como este:: + + sibling_soup = BeautifulSoup("text1text2") + print(sibling_soup.prettify()) + # + # + # + # + # text1 + # + # + # text2 + # + # + # + # + +A tag e a tag estão no mesmo nível: ambas são filhas diretas +da mesma tag. Nós podemos chamá-las irmãs (`siblings`). +Quando um documento é pretty-printed, irmãs aparecem no mesmo nível de identação. +Você pode utilizar esta relação nos códigos que você escrever. + +``.next_sibling`` e ``.previous_sibling`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Você pode usar ``.next_sibling`` e ``.previous_sibling`` para navegar +entre os elementos da página que estão no mesmo nível da árvore:: + + sibling_soup.b.next_sibling + # text2 + + sibling_soup.c.previous_sibling + # text1 + +A tag possui ``.next_sibling``, mas não ``.previous_sibling``, +porque não há nada antes da tag `no mesmo nível na árvore`. +Pela mesma razão, a tag possui ``.previous_sibling`` +mas não ``.next_sibling``:: + + print(sibling_soup.b.previous_sibling) + # None + print(sibling_soup.c.next_sibling) + # None + +As strings "text1" e "text2" `não` são irmãs, porque elas não tem a mesma tag mãe:: + + sibling_soup.b.string + # u'text1' + + print(sibling_soup.b.string.next_sibling) + # None + +No mundo real, ``.next_sibling`` ou ``.previous_sibling`` de uma tag +geralmente são strings contendo espaços em branco. Voltando ao documento +"three sisters":: + + Elsie + Lacie + Tillie + +Você pode pensar que o ``.next_sibling`` da primeira tag será a segunda tag . +Mas na verdade é uma string: a vírgula e um caracter de nova linha (\n) que separam +a primeira da segunda tag :: + + link = soup.a + link + # Elsie + + link.next_sibling + # u',\n' + +A segunda tag é, na verdade, a ``.next_sibling`` da vírgula:: + + link.next_sibling.next_sibling + # Lacie + +.. _sibling-generators: + +``.next_siblings`` e ``.previous_siblings`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Você pode iterar sobre as tag's filhas com ``.next_siblings`` +ou ``.previous_siblings``:: + + for sibling in soup.a.next_siblings: + print(repr(sibling)) + # u',\n' + # Lacie + # u' and\n' + # Tillie + # u'; and they lived at the bottom of a well.' + # None + + for sibling in soup.find(id="link3").previous_siblings: + print(repr(sibling)) + # ' and\n' + # Lacie + # u',\n' + # Elsie + # u'Once upon a time there were three little sisters; and their names were\n' + # None + +Indo e voltando +---------------- + +Dê uma olhada no início do documento "three sisters":: + + The Dormouse's story +

The Dormouse's story

+ +Um parser HTML transforma estas strings em uma série de eventos: "abrir +uma tag ", "abrir uma tag ", "abrir uma tag ", +"adicionar uma string", "fechar uma tag <title>, +"abrir uma tag <p>", e daí por diante. O Beautiful Soup oferece ferramentas +para reconstruir a análise inicial do documento. + +.. _element-generators: + +``.next_element`` e ``.previous_element`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +O atributo ``.next_element`` de uma string ou tag aponta para +qualquer coisa que tenha sido interpretado posteriormente. +Isso deveria ser o mesmo que ``.next_sibling``, mas é +drasticamente diferente. + +Aqui está a tag <a> final no "three sisters". Sua +``.next_sibling`` é uma string: a conclusão da sentença +que foi interrompida pelo início da tag <a>.:: + + last_a_tag = soup.find("a", id="link3") + last_a_tag + # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> + + last_a_tag.next_sibling + # '; and they lived at the bottom of a well.' + +Mas no ``.next_element`` da tag <a>, o que é analisado imediatamente +depois da tag <a> `não` é o resto da sentença: é a palavra "Tillie". + + last_a_tag.next_element + # u'Tillie' + +Isso porque na marcação original, a palavra "Tillie" apareceu +antes do ponto e virgula. O parser encontrou uma tag <a>, então +a palavra "Tillie", então fechando a tag </a>, então o ponto e vírgula e o +resto da sentença. O ponto e vírgula estão no mesmo nível que a tag <a>, +mas a palavra "Tillie" foi encontrada primeiro. + +O atributo ``.previous_element`` é exatamente o oposto de +``.next_element``. Ele aponta para qualquer elemento que +seja analisado antes do respectivo:: + + last_a_tag.previous_element + # u' and\n' + last_a_tag.previous_element.next_element + # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> + +``.next_elements`` e ``.previous_elements`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Você deve ter entendido a idéia agora. Você pode usar estes iteradores +para andar para frente e para atrás no documento quando ele for analisado:: + + for element in last_a_tag.next_elements: + print(repr(element)) + # u'Tillie' + # u';\nand they lived at the bottom of a well.' + # u'\n\n' + # <p class="story">...</p> + # u'...' + # u'\n' + # None + +Buscando na árvore +================== + +O Beautiful Soup define vários métodos para buscar na árvore que está sendo analisada, +mas eles são todos muito similares. Vou usar a maior parte do tempo para explicar os dois mais +populares métodos: ``find()`` e ``find_all()``. Os outros métodos recebem exatamente +os mesmos argumentos, portanto, vou cobrí-los apenas brevemente. + + +Mais uma vez, utilizarei o documento "three sisters" como exemplo:: + + html_doc = """ + <html><head><title>The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + +Utilizando em um filtro um argumento como ``find_all()``, você pode +"dar um zoom" nas partes do documento que você está interessado. + +Tipos de filtros +---------------- + +Antes de entrar em detalhes sobre o ``find_all()`` e métodos similares, +quero mostrar exemplos de diferentes filtros que você pode passar dentro +destes métodos. Estes filtros aparecerão de novo e de novo por toda API +de pesquisa. Você pode usá-los para realizar filtros baseados nos nomes das tags, +nos seus atributos, no texto de uma strings ou em alguma combinação entre eles. + +.. _uma string: + +Uma string +^^^^^^^^^^ + +O filtro mais simples é uma string. Passando uma string para um método de pesquisa, +o Beautiful Soup irá buscar uma correspondência a esta exata string. O seguinte código +encontrará todas as tags no documento:: + + soup.find_all('b') + # [The Dormouse's story] + +Se você passar uma byte string, o Beautiful Soup assumirá que a string +esta codificada como UTF-8. Você pode evitar isso passando ao invés disso +uma string Unicode. + +.. _uma expressão regular: + +Uma expressão regular (regex) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Se você passar um objeto `regex`, o Beautiful Soup irá +realizar um filtro com ela utilizando seu método ``search()``. +O código seguinte buscará todas as tags as quais os nomes comecem com +a letra "b"; neste caso, a tag e a tag :: + + import re + for tag in soup.find_all(re.compile("^b")): + print(tag.name) + # body + # b + +Este código buscará todas as tags cujo nome contenha a letra "t":: + + for tag in soup.find_all(re.compile("t")): + print(tag.name) + # html + # title + +.. _uma lista: + +Uma lista +^^^^^^^^^ + +Se você passar uma lista, o Beautiful Soup irá buscar +uma correspondência com qualquer item dessuma lista. +O código seguinte buscará todas as tags e todas +as tags :: + + soup.find_all(["a", "b"]) + # [The Dormouse's story, + # Elsie, + # Lacie, + # Tillie] + +.. _the value True: + +``True`` +^^^^^^^^ + +O valor ``True`` irá corresponder com tudo. +O código abaixo encontrará ``todas`` as tags do documento, +mas nenhuma das strings:: + + for tag in soup.find_all(True): + print(tag.name) + # html + # head + # title + # body + # p + # b + # p + # a + # a + # a + # p + +.. _a function: + +Uma function +^^^^^^^^^^^^ + +Se nenhuma das opções anteriores funcionar para você, defina uma +função que pegará um elemento como seu único argumento. A função +deverá retornar ``True`` se o argumento corresponder e ``False`` +caso contrário. + +Aqui você tem uma função que irá retornar ``True`` se uma tag definir +o atributo `class`, mas não definir o atributo `id`:: + + def has_class_but_no_id(tag): + return tag.has_attr('class') and not tag.has_attr('id') + +Passe esta função dentro de ``find_all()`` e você irá retornar todas +as tags

:: + + soup.find_all(has_class_but_no_id) + # [

The Dormouse's story

, + #

Once upon a time there were...

, + #

...

] + +Esta função irá encontrar apenas as tags

. Não irá encontrar as tags , +porque elas definem "class e "id" ao mesmo tempo. Ela não encontrará +as tags e , porque estas tags não definem um atributo +"class". + +Se você passar uma função para filtrar um atributo específico como +``href``, o argumento passado na função será o nome do atributo e +não toda a tag. Aqui vemos uma função que encontra todas as tags <a> +em que o atributo ``href`` não corresponde a expressão regular passada:: + + def not_lacie(href): + return href and not re.compile("lacie").search(href) + soup.find_all(href=not_lacie) + # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, + # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] + +A função pode ser tão complexa quanto você precise que seja. +Aqui temos uma função que retorna ``True`` se uma tag esta +cercada por objetos string:: + + from bs4 import NavigableString + def surrounded_by_strings(tag): + return (isinstance(tag.next_element, NavigableString) + and isinstance(tag.previous_element, NavigableString)) + + for tag in soup.find_all(surrounded_by_strings): + print tag.name + # p + # a + # a + # a + # p + +Agora nós estamos prontos para olhar os métodos de busca em detalhes. + +``find_all()`` +-------------- + +Definição: find_all(:ref:`name <name>`, :ref:`attrs <attrs>`, :ref:`recursive +<recursive>`, :ref:`string <string>`, :ref:`limit <limit>`, :ref:`**kwargs <kwargs>`) + +O método ``find_all()`` busca entre os decendentes de uma tag e retorna todos os decendentes +que correspondem a seus filtros. Dei diversos exemplos em `Tipos de filtros`_, +mas aqui estão mais alguns:: + + soup.find_all("title") + # [<title>The Dormouse's story] + + soup.find_all("p", "title") + # [

The Dormouse's story

] + + soup.find_all("a") + # [Elsie, + # Lacie, + # Tillie] + + soup.find_all(id="link2") + # [Lacie] + + import re + soup.find(string=re.compile("sisters")) + # u'Once upon a time there were three little sisters; and their names were\n' + +Alguns podem parecer familiares, mas outros são novos. +O que significa passar um valor ``string`` ou ``id``? Por que +``find_all("p", "title")`` encontra uma tag

com a classe CSS "title"? +Vamos dar uma olhada nos argumentos de ``find_all()``. + +.. _name: + +O argumento ``name`` +^^^^^^^^^^^^^^^^^^^^ + +Passe um valor para ``name`` e você dirá para o Beautiful Soup +considerar apenas as tags com certos nomes. Strings de texto seão ignoradas, +assim como os nomes que não corresponderem ao argumento ``name`` + +Este é o uso mais simples:: + + soup.find_all("title") + # [The Dormouse's story] + +Lembre-se de `Tipos de filtros`_ que o valor para ``name`` pode ser `uma +string`_, `uma expressão regular`_, `uma lista`_, `uma função`_, ou `o valor +True`_. + +.. _kwargs: + +Os argumentos "palavras-chave" +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Qualquer argumento que não for reconhecido se tornará um filtro +de atributos da tag. Se você passar um valor para um argumento +chamado ``id``, o Beautiful Soup irá buscar correspondentes entre +todas tags ``id``:: + + soup.find_all(id='link2') + # [Lacie] + +Se você passar um valor para ``href``, o Beautiful Soup buscar correspondentes +em cada tag que possua o atributo ``href``:: + + soup.find_all(href=re.compile("elsie")) + # [Elsie] + +Você pode filtrar um atributo baseado em `uma string`_, `uma regular +expression`_, `uma lista`_, `uma função`_, ou `no valor True`_. + +Este código encontra todas as tags em que o atributo ``id`` +possuem um valor, independente de qual valor seja:: + + soup.find_all(id=True) + # [Elsie, + # Lacie, + # Tillie] + +Você pode filtrar múltiplos atributos de uma vez passando mais de um argumento +palavra-chave:: + + soup.find_all(href=re.compile("elsie"), id='link1') + # [three] + +Alguns atributos, como o atributo data-* do HTML5, possuem nomes que não +podem ser usados como argumentos palavra-chave::: + + data_soup = BeautifulSoup('

foo!
') + data_soup.find_all(data-foo="value") + # SyntaxError: keyword can't be an expression + +Você pode usar estes atributos para realizar buscas, colocando-os +em um dicionário e passando o dicionário em ``find_all()``, como o argumento +``attrs``:: + + data_soup.find_all(attrs={"data-foo": "value"}) + # [
foo!
] + +Você não pode utilizar um argumento palavra-chave para buscar pelo elemento +HTML "name", porque o Beautiful Soup utiliza o argumento ``name`` para +conter o nome da própria tag. Ao invés disso, você pode passar o valor para +"name" no argumento ``attrs``:: + + name_soup = BeautifulSoup('') + name_soup.find_all(name="email") + # [] + name_soup.find_all(attrs={"name": "email"}) + # [] + +.. _attrs: + +Buscando por uma classe CSS +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +É muito útil buscar por uma tag que tem uma certa classe CSS, mas +o nome do atributo CSS, "class", é uma palavra reservada no Python. +Utilizar ``class`` como um argumento palavra-chave lhe trará um erro +de sintaxe. A partir do Beautiful Soup 4.1.2, você pode buscar por uma +classe CSS utilizando o argumento palavra-chave ``class_``:: + + soup.find_all("a", class_="sister") + # [Elsie, + # Lacie, + # Tillie] + +Assim como qualquer argumento palavra-chave, você pode passar para ``class_`` +uma string, uma expressão regular (regex), uma função ou ``True``:: + + soup.find_all(class_=re.compile("itl")) + # [

The Dormouse's story

] + + def has_six_characters(css_class): + return css_class is not None and len(css_class) == 6 + + soup.find_all(class_=has_six_characters) + # [Elsie, + # Lacie, + # Tillie] + +:ref:`Lembre-se ` que uma tag pode ter valores múltiplos +para seu atributo classe. Quando você buscar por uma tag que tenha +uma certa classe CSS, você esta buscando correspodência em `qualquer` +de suas classes CSS:: + + css_soup = BeautifulSoup('

') + css_soup.find_all("p", class_="strikeout") + # [

] + + css_soup.find_all("p", class_="body") + # [

] + +Você pode também buscar por uma string exata como valor de ``class``:: + + css_soup.find_all("p", class_="body strikeout") + # [

] + +Mas ao procurar por variações de uma string, isso não irá funcionar:: + + css_soup.find_all("p", class_="strikeout body") + # [] + +Se voce quiser buscar por tags que correspondem a duas ou mais classes CSS, +você deverá utilizar um seletor CSS:: + + css_soup.select("p.strikeout.body") + # [

] + +Em versões mais antigas do Beautiful Soup, as quais não possuem o atalho ``class_`` +você pode utilizar o truque ``attrs`` conforme mencionado acima. Será criado um dicionário +do qual o valor para "class" seja uma string ( ou uma expressão regular, ou qualquer +outra coisa) que você queira procurar:: + + soup.find_all("a", attrs={"class": "sister"}) + # [Elsie, + # Lacie, + # Tillie] + +.. _string: + +O argumento ``string`` +^^^^^^^^^^^^^^^^^^^^^^^ + +Com ``string`` você pode buscar por strings ao invés de tags. Assim como +``name`` e os argumentos palavras-chave, você pode passar `uma string`_, `uma +expressão regular`_, `uma lista`_, `uma função`_, ou `o valor True`_. +Aqui estão alguns exemplos:: + + soup.find_all(string="Elsie") + # [u'Elsie'] + + soup.find_all(string=["Tillie", "Elsie", "Lacie"]) + # [u'Elsie', u'Lacie', u'Tillie'] + + soup.find_all(string=re.compile("Dormouse")) + [u"The Dormouse's story", u"The Dormouse's story"] + + def is_the_only_string_within_a_tag(s): + """Return True if this string is the only child of its parent tag.""" + return (s == s.parent.string) + + soup.find_all(string=is_the_only_string_within_a_tag) + # [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...'] + +Mesmo que ``string`` seja para encontrar strings, você pode combiná-lo com argumentos +para encontrar tags: o Beautiful Soup encontrará todas as tags as quais +``.string`` corresponder seu valor em ``string``. O código seguinte encontra +a tag , a qual a ``.string`` é "Elsie":: + + soup.find_all("a", string="Elsie") + # [Elsie] + +O argumento ``string`` é novo no Beautiful Soup 4.4.0. Em versões anteriores +ele era chamado de ``text``:: + + soup.find_all("a", text="Elsie") + # [Elsie] + +.. _limit: + +O argumento ``limit`` +^^^^^^^^^^^^^^^^^^^^^^ + +``find_all()`` retorna todas as tags e strings que correspondem aos seus +filtros. Isso pode levar algum tmepo se o documento for extenso. Se você +não precisar de `todos` os resultados, você pode passar um número limite +(``limit``). Ele funciona assim como o parâmetro LIMIT utilizado em SQL. +Ele diz ao Beautiful Soup para parar de adquirir resultados assim que atingir +um certo número. + +Existem três links no documento "three sisters", mas este código encontra somente +os dois primeiros:: + + soup.find_all("a", limit=2) + # [Elsie, + # Lacie] + +.. _recursive: + +O argumento ``recursive`` +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Se você chamar ``mytag.find_all()``, o Beautiful Soup irá examinar todos os descendentes +de ``mytag``: suas filhas, as filhas de suas filhas e daí em diante. Se você quer apenas que +o Beautiful Soup considere filhas diretas, você pode passar o parâmetro ``recursive=False``. +Veja a diferença aqui:: + + soup.html.find_all("title") + # [The Dormouse's story] + + soup.html.find_all("title", recursive=False) + # [] + +Aqui está o trecho do documento:: + + + + + The Dormouse's story + + + ... + +O tag esta abaixo da tag <html>, mas não está `diretamente` +abaixo de <html>: a tag <head> está no caminho entre elas. O Beautiful Soup encontra a tag +<title> quando é autorizado a olhar todos os descendentes de <html>, mas +quando ``recursive=False`` é restringido o acesso as filhas imediatas de <html>. + +O Beautiful Soup oferece diversos métodos de busca na árvore (como vimos acima), e a maioria +deles recebe os mesmos argumentos que ``find_all()``: ``name``, +``attrs``, ``string``, ``limit``, e os argumentos palavras-chave. Mas o +argumento ``recursive`` é diferente: ``find_all()`` e ``find()`` são +os únicos métodos que o suportam. Passar ``recursive=False`` em um método +como ``find_parents()`` não seria muito útil. + +Chamar uma tag é como chamar ``find_all()`` +-------------------------------------------- + +Por ``find_all()`` ser o método mais popular na API de busca do +Beautiful Soup, você pode usar um atalho para ele. Se você tratar +o objeto ``BeautifulSoup`` ou um objeto ``Tag`` como se fosse uma +função, então é o mesmo que chamar ``find_all()`` para aquele objeto. +Estas duas linhas de código são equivalentes:: + + soup.find_all("a") + soup("a") + +Estas duas linhas também são equivalentes:: + + soup.title.find_all(string=True) + soup.title(string=True) + +``find()`` +---------- + +Signature: find(:ref:`name <name>`, :ref:`attrs <attrs>`, :ref:`recursive +<recursive>`, :ref:`string <string>`, :ref:`**kwargs <kwargs>`) + +O método ``find_all()`` varre todo o documento em busca de resultados, +mas algumas vezes você irá querer apenas um resultado. Se você sabe que +o documento possui apenas uma tag <body>, é perda de tempo varrer todo o +o documento procurando por outras. Ao invés de passar ``limit=1`` +toda vez em que chamar ``find_all``, você pode usar o método ``find()``. +Estas duas linhas de código são `quase` equivalentes:: + + soup.find_all('title', limit=1) + # [<title>The Dormouse's story] + + soup.find('title') + # The Dormouse's story + +A única diferença é que ``find_all()`` retorna uma lista contendo apenas +um resuldado, enquanto ``find()`` retorna o resultado. + +Se ``find_all()`` não encontrar nada, ele retornará uma lista vazia. Se +``find()`` não encontrar nada, ele retornará ``None``:: + + print(soup.find("nosuchtag")) + # None + +Lembre-se do truque ``soup.head.title`` de `Navegar usando os nomes das tags`_? +Aquele truque funciona chamando repetidamente ``find()``:: + + soup.head.title + # The Dormouse's story + + soup.find("head").find("title") + # The Dormouse's story + +``find_parents()`` e ``find_parent()`` +---------------------------------------- + +Signature: find_parents(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) + +Signature: find_parent(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) + +Levei muito tempo cobrindo ``find_all()`` e ``find()`` acima. +O API do Beautiful Soup define dez outros métodos +para buscas na árvore, mas não tenha medo! Cinco destes métodos são +basicamente o mesmo que ``find_all()``, e os outros cinco são basicamente +o mesmo que ``find()``. A única diferença está em qual parte da árvore +eles procuram. + +Primeiro vamos considerar ``find_parents()`` e +``find_parent()``. Lembre-se que ``find_all()`` e ``find()`` trabalham +de sua própria maneira descendo através da árvore, procurando pelos +descendentes de uma tag. Estes métodos fazem o contrário: eles trabalham +`subindo` a árvore, procurando pelas `mães` de uma tag (ou string). +Vamos experimentá-los: começando por uma string "enterrada" no documento +"three daughters":: + + a_string = soup.find(string="Lacie") + a_string + # u'Lacie' + + a_string.find_parents("a") + # [Lacie] + + a_string.find_parent("p") + #

Once upon a time there were three little sisters; and their names were + # Elsie, + # Lacie and + # Tillie; + # and they lived at the bottom of a well.

+ + a_string.find_parents("p", class="title") + # [] + +Uma das três tags é diretamente um nível superior da string em +questão, então nossa busca a encontra. Uma das três tags

é uma mãe +indireta da string e nossa busca também a encontra. Há uma tag

com +a classe CSS "title" em algum lugar no documento, mas não é nenhuma das tags mães +da string, portanto, não podemos encontrá-la com ``find_parents()``. + +Você já deve ter feito a conexão entre ``find_parent()`` e +``find_parents()``, e os atributos `.parent`_ e `.parents`_ mencionados +anteriormente. A conexão é muito forte. Estes métodos de busca utilizam ``.parents`` +para iterar sobre todos as mãesS e compara cada um com o filtro passado +para verificar se preenche o requisito. + +``find_next_siblings()`` e ``find_next_sibling()`` +---------------------------------------------------- + +Signature: find_next_siblings(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) + +Signature: find_next_sibling(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) + +Estes métodos utilizam :ref:`.next_siblings ` para +iterar sobre o resto dos filhos de um elemento da árvore. O método +``find_next_siblings()`` retornará todos os filhos que atendem o +requisito ``find_next_sibling()`` retorna apenas o primeiro:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_next_siblings("a") + # [Lacie, + # Tillie] + + first_story_paragraph = soup.find("p", "story") + first_story_paragraph.find_next_sibling("p") + #

...

+ +``find_previous_siblings()`` e ``find_previous_sibling()`` +------------------------------------------------------------ + +Signature: find_previous_siblings(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) + +Signature: find_previous_sibling(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) + +Estes métodos utilizam :ref:`.previous_siblings ` para iterar sobre os filhos de um elemento que +o precede na árvore. O método ``find_previous_siblings()`` +retorna todos os filhos que atendem o requisito e ``find_previous_sibling()``retorna apenas o primeiro:: + + last_link = soup.find("a", id="link3") + last_link + # Tillie + + last_link.find_previous_siblings("a") + # [Lacie, + # Elsie] + + first_story_paragraph = soup.find("p", "story") + first_story_paragraph.find_previous_sibling("p") + #

The Dormouse's story

+ + +``find_all_next()`` e ``find_next()`` +--------------------------------------- + +Signature: find_all_next(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) + +Signature: find_next(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) + +Estes métodos utilizam :ref:`.next_elements ` para +iterar sobre qualquer tag e string que aparecer depois da atual no documento. +O método ``find_all_next()`` retorna todos os casos que atendem, e +``find_next()`` retorna somente o primeiro caso:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_all_next(string=True) + # [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'] + + first_link.find_next("p") + #

...

+ +No primeiro exemplo, a string "Elsie" foi encontrada, mesmo estando +dentro da tag . No segundo exemplo, a última tag

do documento foi +encontrada, mesmo que não esteja na mesma parte da árvore que onde começamos. +Para estes métodos, o que importa é que um elemento corresponda ao filtro e esteja +depois do elemento de início no documento. + +``find_all_previous()`` e ``find_previous()`` +----------------------------------------------- + +Signature: find_all_previous(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) + +Signature: find_previous(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) + +Estes métodos utilizam :ref:`.previous_elements ` para +iterar sobre as tags e strings que aparecem antes do elemento indicado no argumento. +O método ``find_all_previous()`` retorna todos que correspondem a busca e o método +``find_previous()`` apenas a primeira correspondência:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_all_previous("p") + # [

Once upon a time there were three little sisters; ...

, + #

The Dormouse's story

] + + first_link.find_previous("title") + # The Dormouse's story + +Quando se chama ``find_all_previous("p")`` é encontrado não só o +primeiro parágrafo do documento (o que possui class="title"), mas também o +segundo parágrafo, a tag

que contém a tag por onde começamos. +Isso não deveria ser tão surpreendente: nós estamos olhando para todas as tags +que apareceram anteriormente no documento incluindo aquela onde começamos. Uma +tag

que contenha uma tag deve aparecer antes da tag que ela contém. + +Seletores CSS +------------- + +A partir da versão 4.7.0, o Beautiful Soup suporta a maior parte dos seletores CSS4 +através do projeto `SoupSieve `_. Se você +instalou o Beautiful Soup através do ``pip``,o SoupSieve foi instalado ao mesmo tempo, +portanto você não precisará realizar nenhuma etapa adicional. + +``BeautifulSoup`` possui um método ``.select()`` o qual utiliza o SoupSieve para +executar um seletor CSS selector sobre um documento a ser analisado e retorna todos os +elementos correspondentes. ``Tag`` possui um método similar que executa um seletor CSS +sobre o conteúdo de uma única tag. + +(Versões anteriores do Beautiful Soup também possuem o método ``.select()``, + mas somente os seletores CSS mais populares são suportados. + +A `documentação `_ SoupSieve +lista todos os seletores suportados atualmente, mas aqui estão alguns dos +básicos:: + +Você pode encontrar tags:: + + soup.select("title") + # [The Dormouse's story] + + soup.select("p:nth-of-type(3)") + # [

...

] + +Encontrar tags aninhadas com outras:: + soup.select("body a") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("html head title") + # [The Dormouse's story] + +Encontrar tags `diretamente` abaixo de outras tags no aninhamento:: + + soup.select("head > title") + # [The Dormouse's story] + + soup.select("p > a") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("p > a:nth-of-type(2)") + # [Lacie] + + soup.select("p > #link1") + # [Elsie] + + soup.select("body > a") + # [] + +Encontrar as irmãs de alguma tag:: + + soup.select("#link1 ~ .sister") + # [Lacie, + # Tillie] + + soup.select("#link1 + .sister") + # [Lacie] + +Encontrar tags pela classe CSS:: + + soup.select(".sister") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("[class~=sister]") + # [Elsie, + # Lacie, + # Tillie] + +Encontrar tags pelo ID:: + + soup.select("#link1") + # [Elsie] + + soup.select("a#link2") + # [Lacie] + +Encontrar tags que se relacionam com qualquer seletor em uma lista de seletores:: + + soup.select("#link1,#link2") + # [Elsie, + # Lacie] + +Testar a existência de um atributo:: + + soup.select('a[href]') + # [Elsie, + # Lacie, + # Tillie] + +Encontrar tags pelo valor do atributo:: + + soup.select('a[href="http://example.com/elsie"]') + # [Elsie] + + soup.select('a[href^="http://example.com/"]') + # [Elsie, + # Lacie, + # Tillie] + + soup.select('a[href$="tillie"]') + # [Tillie] + + soup.select('a[href*=".com/el"]') + # [Elsie] + +Há outro método chamado ``select_one()``, o qual encontra somente +a primeira tag que combina com um seletor:: + + soup.select_one(".sister") + # Elsie + +Se você analisou um XML que define namespaces, você pode +utilizar nos seletores CSS:: + + from bs4 import BeautifulSoup + xml = """ + I'm in namespace 1 + I'm in namespace 2 + """ + soup = BeautifulSoup(xml, "xml") + + soup.select("child") + # [I'm in namespace 1, I'm in namespace 2] + + soup.select("ns1|child", namespaces=namespaces) + # [I'm in namespace 1] + +Quando manipulando um seletor CSS que utiliza +namespaces,o Beautiful Soup utiliza a abreviação do namespace +que encontrou quando estava analisando o documento. Você pode evitar isso +passando um dicionário com suas próprias abreviações:: + + namespaces = dict(first="http://namespace1/", second="http://namespace2/") + soup.select("second|child", namespaces=namespaces) + # [I'm in namespace 2] + +Todo este negócio de seletor CSS é conveniente +para pessoas que já sabem a sintaxe do seletor CSS. +Você pode fazer tudo isso com a API do BeautifulSoup. +E se os seletores CSS são tudo o que você precisa, +você deveria analisar o documento com lxml: é mais rápido. Mas isso deixa você `combinar` +seletores CSS com a API do Beautiful Soup. + +Modificando a árvore +==================== + +O principal poder do Beautiful Soup está na busca pela árvore, mas você +pode também modificar a árvore e escrever suas modificações como um novo +documento HTML ou XML. + +Alterando nomes de tags e atributos +--------------------------------- + +Cobri este assunto anteriormente em `Atributos`_, mas vale a pena repetir. Você +pode renomear uma tag, alterar o valor de algum de seus atributos, adicionar novos +atributos e deletar qualquer um deles:: + + soup = BeautifulSoup('Extremely bold') + tag = soup.b + + tag.name = "blockquote" + tag['class'] = 'verybold' + tag['id'] = 1 + tag + #
Extremely bold
+ + del tag['class'] + del tag['id'] + tag + #
Extremely bold
+ +Modificando ``.string`` +----------------------- + +Se você definir o um atributo ``.string`` de uma tag, o conteúdo da +tag será substituido pela string que foi passada:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + + tag = soup.a + tag.string = "New link text." + tag + # New link text. + +Cuidado: se a tag conter outra(s) tag(s), ela(s) e todo seu conteúdo +serão destruídos. + +``append()`` +------------ + +Você pode adicionar algo no conteúdo de uma tag com ``Tag.append()``. Funciona +da mesma maneira que ``.append()`` de uma lista:: + + soup = BeautifulSoup("Foo") + soup.a.append("Bar") + + soup + # FooBar + soup.a.contents + # [u'Foo', u'Bar'] + +``extend()`` +------------ + +Com início no Beautiful Soup 4.7.0, ``Tag`` também suporta um método chamado +``.extend()``, o qual funciona da mesma maneira que chamando ``.extend()`` em +uma lista:: + + soup = BeautifulSoup("Soup") + soup.a.extend(["'s", " ", "on"]) + + soup + # Soup's on + soup.a.contents + # [u'Soup', u''s', u' ', u'on'] + +``NavigableString()`` e ``.new_tag()`` +------------------------------------------------- + +Se você precisar adicionar uma string a um documento, sem problema -- você +pode passar uma string Python através de ``append()``, ou você pode chamar +o construtor ``NavigableString``:: + + soup = BeautifulSoup("") + tag = soup.b + tag.append("Hello") + new_string = NavigableString(" there") + tag.append(new_string) + tag + # Hello there. + tag.contents + # [u'Hello', u' there'] + +Se você quiser criar um comentário ou alguma outra subclasse de +``NavigableString``, apenas chame o construtor:: + + from bs4 import Comment + new_comment = Comment("Nice to see you.") + tag.append(new_comment) + tag + # Hello there + tag.contents + # [u'Hello', u' there', u'Nice to see you.'] + +(Esta é uma funcionalidade nova no Beautiful Soup 4.4.0.) + +E se você precisar criar uma nova tag? A melhor solução +é chamar o método ``BeautifulSoup.new_tag()``:: + + soup = BeautifulSoup("") + original_tag = soup.b + + new_tag = soup.new_tag("a", href="http://www.example.com") + original_tag.append(new_tag) + original_tag + # + + new_tag.string = "Link text." + original_tag + # Link text. + +Somente o primeiro argumento (o nome da tag) é obrigatório. + +``insert()`` +------------ + +``Tag.insert()`` funciona assim como ``Tag.append()``, exceto que o novo elemento +não será inserido ao final do ``.contents`` de sua tag mãe. Ele será inserido em qualquer posição +numérica que você informar. Funciona assim como ``.insert()`` em uma lista:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + tag = soup.a + + tag.insert(1, "but did not endorse ") + tag + # I linked to but did not endorse example.com + tag.contents + # [u'I linked to ', u'but did not endorse', example.com] + +``insert_before()`` e ``insert_after()`` +------------------------------------------ + +O método ``insert_before()`` insere tags ou strings imediatamente antes de algo +na árvore:: + + soup = BeautifulSoup("stop") + tag = soup.new_tag("i") + tag.string = "Don't" + soup.b.string.insert_before(tag) + soup.b + # Don'tstop + +O método ``insert_after()`` insere tags ou strings imediatamente após algo +na árvore:: + + div = soup.new_tag('div') + div.string = 'ever' + soup.b.i.insert_after(" you ", div) + soup.b + # Don't you
ever
stop
+ soup.b.contents + # [Don't, u' you',
ever
, u'stop'] + +``clear()`` +----------- + +O ``Tag.clear()`` remove o conteúdo de uma tag:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + tag = soup.a + + tag.clear() + tag + # + +``extract()`` +------------- + +O ``PageElement.extract()`` remove uma tag ou string da árvore. Ele retorna +a tag ou string que foi extraída:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + i_tag = soup.i.extract() + + a_tag + # I linked to + + i_tag + # example.com + + print(i_tag.parent) + None + +Neste ponto você efetivamente tem duas árvores de análise: uma baseada no objeto +``BeautifulSoup`` que você usou para analisar o documento, e outra baseada na tag que foi +extraída. Você pode também chamar ``extract`` em um filho do elemento que você extraiu:: + + my_string = i_tag.string.extract() + my_string + # u'example.com' + + print(my_string.parent) + # None + i_tag + # + + +``decompose()`` +--------------- + +O ``Tag.decompose()`` remove uma tag da árvore, então destrói `completamente` ela +e seu conteúdo:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + soup.i.decompose() + + a_tag + # I linked to + + +.. _replace_with(): + +``replace_with()`` +------------------ + +Um ``PageElement.replace_with()`` remove uma tag ou string da árvore e +substitui pela tag ou string que você escolher:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + new_tag = soup.new_tag("b") + new_tag.string = "example.net" + a_tag.i.replace_with(new_tag) + + a_tag + # I linked to example.net + +``replace_with()`` retorna a tag ou string que foi substituída, então você pode +examiná-la ou adicioná-la novamente em outra parte da árvore. + +``wrap()`` +---------- + +O ``PageElement.wrap()`` envelopa um elemento na tag que você especificar. Ele +retornará o novo empacotador:: + + soup = BeautifulSoup("

I wish I was bold.

") + soup.p.string.wrap(soup.new_tag("b")) + # I wish I was bold. + + soup.p.wrap(soup.new_tag("div") + #

I wish I was bold.

+ +Este método é novo no Beautiful Soup 4.0.5. + +``unwrap()`` +--------------------------- + +O ``Tag.unwrap()`` é o oposto de ``wrap()``. Ele substitui uma tag pelo +que estiver dentro dela. É uma boa maneira de remover marcações:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + a_tag.i.unwrap() + a_tag + # I linked to example.com + +Assim como ``replace_with()``, ``unwrap()`` retorna a tag que foi +substituída. + +``smooth()`` +--------------------------- + +Após chamar vários métodos que modificam a árvore, você pode acabar com um ou dois objetos ``NavigableString`` próximos um ao outro. O Beautiful Soup não tem nenhum problema com isso, mas como isso não pode acontecer em um documento que acabou de ser analisado, você não deve esperar um comportamento como o seguinte:: + + soup = BeautifulSoup("

A one

") + soup.p.append(", a two") + + soup.p.contents + # [u'A one', u', a two'] + + print(soup.p.encode()) + #

A one, a two

+ + print(soup.p.prettify()) + #

+ # A one + # , a two + #

+ +Você pode chamar ``Tag.smooth()`` para limpar a árvore analisada, consolidando strings adjacentes:: + + soup.smooth() + + soup.p.contents + # [u'A one, a two'] + + print(soup.p.prettify()) + #

+ # A one, a two + #

+ +O método ``smooth()`` é novo no Beautiful Soup 4.8.0. + +Saída +====== + +.. _.prettyprinting: + +Pretty-printing +--------------- + +O método ``prettify()`` irá transformar uma árvore do Beautiful Soup em +uma string Unicode devidamente formatada, com uma linha para cada tag e cada string:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + soup.prettify() + # '\n \n \n \n \n...' + + print(soup.prettify()) + # + # + # + # + # + # I linked to + # + # example.com + # + # + # + # + +Você pode chamar ``prettify()`` no top-level do objeto ``BeautifulSoup``, +ou em qualquer de seus objetos ``Tag``:: + + print(soup.a.prettify()) + # + # I linked to + # + # example.com + # + # + +Non-pretty printing +------------------- + +Se você quer apenas uma string, sem nenhuma formatação, você pode chamar +``unicode()`` ou ``str()`` para o objeto ``BeautifulSoup`` ou uma ``Tag`` +dentro dele:: + + str(soup) + # 'I linked to example.com' + + unicode(soup.a) + # u'I linked to example.com' + +A função ``str()`` retorna uma string codificada em UTF-8. Veja +`Encodings`_ para outras opções. + +Você também pode chamar ``encode()`` para ter uma bytestring, e ``decode()`` +para ter Unicode. + +.. _output_formatters: + +Output formatters +----------------- + +Se você der para o Beautiful Soup um documento que contém entidades HTML como +"&lquot;", elas serão convertidades em caracteres Unicode:: + + soup = BeautifulSoup("“Dammit!” he said.") + unicode(soup) + # u'\u201cDammit!\u201d he said.' + +Se você converter o documento em uma string, os caracteres Unicode +serão codificados como UTF-8. Você não irá ter suas entidades HTML de volta:: + + str(soup) + # '\xe2\x80\x9cDammit!\xe2\x80\x9d he said.' + +Por padrão, os únicos caracteres que escapam desta saída são o & e os sinais de <>. +Eles são convertidos em "&", "<", +e ">", com isso o Beautiful Soup não gera HTML e XML inválidos de maneira inadvertida. + + soup = BeautifulSoup("

The law firm of Dewey, Cheatem, & Howe

") + soup.p + #

The law firm of Dewey, Cheatem, & Howe

+ + soup = BeautifulSoup('A link') + soup.a + # A link + +Você pode alterar este comportamento informando um valor para o argumento de +``formatter`` para ``prettify()``, ``encode()``, ou +``decode()``. Beautiful Soup reconhece cinco possiveis valores para ``formatter``. + +O padrão é ``formatter="minimal"``. Strings sempre serão processadas de maneira a garantir que o Beautiful Soup gere HTML/XML válidos:: + + french = "

Il a dit <<Sacré bleu!>>

" + soup = BeautifulSoup(french) + print(soup.prettify(formatter="minimal")) + # + # + #

+ # Il a dit <<Sacré bleu!>> + #

+ # + # + +Se você passar ``formatter="html"``, Beautiful Soup irá converter caracteres +Unicode para entidades HTML sempre que possível:: + + print(soup.prettify(formatter="html")) + # + # + #

+ # Il a dit <<Sacré bleu!>> + #

+ # + # + +Se você passar um ``formatter="html5"``, é o mesmo que ``formatter="html"``, +mas o Beautiful Soup irá omitir a barra de fechamento HTML:: + + soup = BeautifulSoup("
") + + print(soup.encode(formatter="html")) + #
+ + print(soup.encode(formatter="html5")) + #
+ +Se você passar ``formatter=None``, Beautiful Soup não irá modificar +as strings na saída. Esta é a opção mais rápida, mas permitirá que o +Beautiful Soup gere HTML/XML inválidos, como nestes exemplos:: + + print(soup.prettify(formatter=None)) + # + # + #

+ # Il a dit <> + #

+ # + # + + link_soup = BeautifulSoup('A link') + print(link_soup.a.encode(formatter=None)) + # A link + +Se você precisar de controles mais sofisticados sobre sua saída, +você pode usar a classe ``Formatter`` do Beautiful Soup. Aqui você pode ver um +formatter que converte strings para uppercase, quando elas ocorrem em um nó de texto +ou em um valor de algum atributo:: + + from bs4.formatter import HTMLFormatter + def uppercase(str): + return str.upper() + formatter = HTMLFormatter(uppercase) + + print(soup.prettify(formatter=formatter)) + # + # + #

+ # IL A DIT <> + #

+ # + # + + print(link_soup.a.prettify(formatter=formatter)) + # + # A LINK + # + +Dividindo em subclasses ``HTMLFormatter`` ou ``XMLFormatter`` darão a você ainda +mais controle sobre a saída. Por exemplo, o Beautiful Soup ordena os atributos em toda +tag por padrão:: + + attr_soup = BeautifulSoup(b'

') + print(attr_soup.p.encode()) + #

+ +Para desabilitar esta opção, você pode criar uma subclasse do método ``Formatter.attributes()``, +o qual controla qual atributo será usado na saída e em que ordem. Esta +implementação também filtra o atributido chamado "m" quando ele aparece:: + + class UnsortedAttributes(HTMLFormatter): + def attributes(self, tag): + for k, v in tag.attrs.items(): + if k == 'm': + continue + yield k, v + print(attr_soup.p.encode(formatter=UnsortedAttributes())) + #

+ +Um último conselho: se você criar um objeto ``CDATA'', o texto dentro deste objeto +sempre estará presente `exatamente como aparenta, com nenhuma formatação`. +O Beautiful Soup irá chamar sua função de substituição da entidade, apenas +no caso de você ter escrito uma função personalizada que conta todas as strings +que existem no documento ou algo do tipo, mas ele irá ignorar o valor de retorno:: + + from bs4.element import CData + soup = BeautifulSoup("") + soup.a.string = CData("one < three") + print(soup.a.prettify(formatter="xml")) + # + # + # + + +``get_text()`` +-------------- + +Se você quer apenas o texto contido no documento ou em um par de tags, você +pode utilizar o método ``get_text()``. Ele retornará todo texto em um documento +ou dentro das tags como uma string Unicode:: + + markup = '\nI linked to example.com\n' + soup = BeautifulSoup(markup) + + soup.get_text() + u'\nI linked to example.com\n' + soup.i.get_text() + u'example.com' + +Você pode especificar uma string a ser usada para unir as partes do texto:: + + # soup.get_text("|") + u'\nI linked to |example.com|\n' + +Você pode dizer ao Beautiful Soup para excluir espaços em branco do início +e fim de cada parte de texto:: + + # soup.get_text("|", strip=True) + u'I linked to|example.com' + +Contudo para isso, você pode querer utilizar o gerador :ref:`.stripped_strings ` +e processar o texto você mesmo:: + + [text for text in soup.stripped_strings] + # [u'I linked to', u'example.com'] + +Especificando um interpretador (parser) para uso +================================================ + +Se você precisa analisar um pequeno HTML, você pode passá-lo no construtor do +``BeautifulSoup`` e será o suficiente. O Beautiful Soup irá escolher um parser +para você e irá interpretar o dado. Mas existem alguns argumentos adicionais que você +pode passar no construtor para alterar qual parser será usado. + +O primeiro argumento do construtor ``BeautifulSoup`` é uma string ou uma variável contendo o +conteúdo do que você quer analisar. O segundo argumento é `como` você quer interpretar aquele +conteúdo. + +Se você não especificar nada, você irá utilizar o melhor analisador HTML instalado. +O Beautiful Soup classifica o lxml's como sendo o melhor, logo em seguida o html5lib, +e então o parser nativo do Python. Você pode substituí-lo, especificando de acordo +com as seguintes características: + +* O tipo de marcação que você quer analisar. Atualmente são suportados + "html", "xml", and "html5". +* O nome do parser que você quer utilizar. Atualmente são suportadas +as opções "lxml", "html5lib", e "html.parser" (parser nativo do Python). + +A seção `Instalando um interpretador (parser)`_ compara os parsers suportados. + +Se você não tem um parser apropriado instalado, o Beautiful Soup irá +ignorar sua solicitação e escolher um diferente. Atualmente, o único parser +XML suportado é o lxml. Se você não possui o lxml instalado, pedir um parser +XML não trará um e pedir por "lxml" não funcionará também. + +Diferenças entre os interpretadores (parsers) +------------------------------------------ + +O Beautiful Soup apresenta a mesma interface para diferentes parsers, +mas cada um é diferente. Diferentes parsers irão criar diferentes análises da árvore +do mesmo documento. As maiores diferenças estão entre os parsers HTML e XML. +Aqui está um pequeno documento analisado como HTML:: + + BeautifulSoup("") + # + +Como uma tag vazia não é um HTML válido, o analisador a transforma +em um par . + +Aqui está o mesmo documento analisado como XML (partindo do princípio +que você tenha o lxml instalado). Note que o a tag vazia é deixada sozinha, +e que é dada ao documento uma declaração XML ao invés de ser colocada dentro de uma tag .:: + + BeautifulSoup("", "xml") + # + # + +Há também diferenças entre analisadores HTML. Se você der ao Beautiful +Soup um documento HTML perfeitamente formatado, estas diferenças não irão +importar. Um analisador será mais rápido que outro, mas todos irão lhe +retornar uma estrutura de dados que se parece exatamente como o HTML original. + +Mas se o documento não estiver perfeitamente formatado, diferentes analisadores +irão retornar diferentes resultados. Aqui está um pequeno e inválido documento +analisado utilizando o analisador lxml HTML. Note que a tag pendente

é +simplesmente ignorada:: + + BeautifulSoup("

", "lxml") + #
+ +Aqui está o mesmo documento analisado utilizando html5lib:: + + BeautifulSoup("

", "html5lib") + #

+ +Ao invés de ignorar a tag

pendente, o html5lib a equipara a uma tag +

aberta. Este parser também adiciona uma tag vazia ao documento. + +Aqui está o mesmo documento analisado com o parser HTML nativo do Python:: + + BeautifulSoup("

", "html.parser") + # + +Assim como html5lib, este parser ignora a tag de fechamento

. +Este parser também não realiza nenhuma tentatida de criar um HTML bem +formatado adicionando uma tag . Como lxml, ele nem se importa em +adicionar uma tag . + +Sendo o documento "

" inválido, nenhuma dessas técnicas é a maneira +"correta" de lidar com isso. O html5lib utiliza técnicas que são parte +do padrão HTML5, portanto vendo sendo definido como a maneira "mais correta", +mas todas as três técnicas são legítimas. + +Diferenças entre analisadores podem afetar o seu script. Se você está +planejando distribuir seu script para outras pessoas, ou rodá-lo em +múltiplas máquinas, você deve especificar o analisador no construtor +``BeautifulSoup``. Isso irá reduzir as chances de que seus usuários +analisem um documento de forma diferente da maneira como você analisou. + + +Codificação (Encoding) +====================== + +Todo documento HTML ou XML é escrito em uma codificação (encoding) específica como ASCII +ou UTF-8. Mas quando você carrega um documento no BeautifulSoup, você irá descobrir +que ele foi convertido para Unicode:: + + markup = "

Sacr\xc3\xa9 bleu!

" + soup = BeautifulSoup(markup) + soup.h1 + #

Sacré bleu!

+ soup.h1.string + # u'Sacr\xe9 bleu!' + +Não é mágica (Seria bem legal que fosse). O BeautifulSoup utiliza uma +sub-biblioteca chamada `Unicode, Dammit`_ para detectar a codificação de +um documento e convertê-lo para Unicode. A codificação detectada automaticamente está +disponível como objeto ``.original_encoding`` atributo do objeto ``BeautifulSoup`` :: + + soup.original_encoding + 'utf-8' + +`Unicode, Dammit` acerta na maioria das vezes, mas pode errar em algumas. +Outras vezes acerta, porém somente após uma busca byte a byte no documento, +o leva muito tempo. Se você souber com antecedência a codificação, você poderá +evitar erros ou demora passando-o para o contrutor do ``BeautifulSoup`` +através de ``from_encoding``. + +Abaixo você tem um documento escrito em ISO-8859-8. O documento é tão +pequeno que o `Unicode, Dammit` não consegue verificar sua codificação +e acaba fazendo a identificação como ISO-8859-7:: + + markup = b"

\xed\xe5\xec\xf9

" + soup = BeautifulSoup(markup) + soup.h1 +

νεμω

+ soup.original_encoding + 'ISO-8859-7' + +Podemos consertar isso passando a codificação correta com ``from_encoding``:: + + soup = BeautifulSoup(markup, from_encoding="iso-8859-8") + soup.h1 +

םולש

+ soup.original_encoding + 'iso8859-8' + +Se você não sabe qual a codificação correta, mas você sabe que o +`Unicode, Dammit` está errado, você pode passar as opções excluentes +como ``exclude_encodings``:: + + soup = BeautifulSoup(markup, exclude_encodings=["ISO-8859-7"]) + soup.h1 +

םולש

+ soup.original_encoding + 'WINDOWS-1255' + +Windows-1255 não é 100% correto, mas é um superconjunto compatível com +ISO-8859-8, portanto é mais próximo do ideal. (``exclude_encodings`` +é uma opção nova no Beautiful Soup 4.4.0.) + +Em casos raros (geralmente quando um documento UTF-8 contém texto escrito +em uma codificação completamente diferente), a única maneira de ser convertido para +Unicode é convertendo alguns caracteres com o caractere especial Unicode +"REPLACEMENT CHARACTER" (U+FFFD, �). Se o `Unicode, Dammit` precisar utilizá-lo, +ele será armazenado no atributo ``.contains_replacement_characters`` como +``True`` no ``UnicodeDammit`` ou objeto ``BeautifulSoup``. Isso deixa você ciente +que a representação Unicode não é uma representação exata do original - algum dado +foi perdido. Se um documento possui �, mas ``.contains_replacement_characters`` é ``False``, +você poderá concluir então que o � já estava ali originalmente e não representa dados +perdidos. + +Codificação de Saída +-------------------- + +Quando um documento é gerado pelo Beautiful Soup, ele é gerado como UTF-8, +mesmo que o documento não for um UTF-8 de início. Aqui está um documento gerado +com codificação Latin-1:: + + markup = b''' + + + + + +

Sacr\xe9 bleu!

+ + + ''' + + soup = BeautifulSoup(markup) + print(soup.prettify()) + # + # + # + # + # + #

+ # Sacré bleu! + #

+ # + # + +Note que a tag foi reescrita para refletir o fato que o documento +é agora um UTF-8. + +Se você não quiser um UTF-8, você pode passar a codificação desejada como parâmetro de +``prettify()``:: + + print(soup.prettify("latin-1")) + # + # + # + # ... + +Você também pode chamar encode() no objeto ``BeautifulSoup`` ou em qualquer elemento +do objeto, assim como se faz em uma string Python:: + + soup.p.encode("latin-1") + # '

Sacr\xe9 bleu!

' + + soup.p.encode("utf-8") + # '

Sacr\xc3\xa9 bleu!

' + +Qualquer caractere que não pode ser representado na codificação escolhida +irá ser convertida para uma entidade de referência numérica XML. Abaixo você +tem um documento que inclui o caractere Unicode SNOWMAN:: + + markup = u"\N{SNOWMAN}" + snowman_soup = BeautifulSoup(markup) + tag = snowman_soup.b + +O caractere SNOWMAN faz parte da documentação UTF-8 (algo como +☃), mas não possui representação para este caractere em ISO-latin-1 ou +ASCII, portanto ele é convertido para "☃" para as essas codificações:: + + print(tag.encode("utf-8")) + # + + print tag.encode("latin-1") + # + + print tag.encode("ascii") + # + +Unicode, Dammit +--------------- + +Você pode usar o `Unicode, Dammit` fora do Beautiful Soup. É útil +quando você possui dados em uma codificação desconhecida e quer +simplesmente convertê-la para Unicode:: + + from bs4 import UnicodeDammit + dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!") + print(dammit.unicode_markup) + # Sacré bleu! + dammit.original_encoding + # 'utf-8' + + +As respostas do `Unicode, Dammit` serão um pouco mais precisas se você +instalar as bibliotecas ``chardet`` ou ``cchardet``. Quanto maior a quantidade +de dados no arquivo que você passar para o `Unicode, Dammit`, mais precisas serão +as conversões. Se você possui suas suspeitas sobre qual a codificação original, +você pode passar as opções em uma lista:: + + dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"]) + print(dammit.unicode_markup) + # Sacré bleu! + dammit.original_encoding + # 'latin-1' + +`Unicode, Dammit` possui duas características que o Beautiful Soup não utiliza. + +Smart quotes +^^^^^^^^^^^^ + +Você pode utilizar `Unicode, Dammit` para converter Microsoft smart quotes para +entidades HTML ou XML:: + + markup = b"

I just \x93love\x94 Microsoft Word\x92s smart quotes

" + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup + # u'

I just “love” Microsoft Word’s smart quotes

' + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup + # u'

I just “love” Microsoft Word’s smart quotes

' + +Você também pode converter Microsoft smart quotes para ASCII:: + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup + # u'

I just "love" Microsoft Word\'s smart quotes

' + +Espero que você ache estas características úteis, mas o Beautiful Soup não +as usa.O Beautiful Soup dá preferência ao comportamento padrão, que é +converter para caracteres Unicode:: + + UnicodeDammit(markup, ["windows-1252"]).unicode_markup + # u'

I just \u201clove\u201d Microsoft Word\u2019s smart quotes

' + +Codificação Inconsistente +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Algumas vezes um documento é em sua maioria UTF-8, mas contém caracteres +Windows-1252 assim como (de novo) Microsoft smart quotes. Isso pode acontecer +quando um website compostos de dados de muitas fontes diferentes. Você pode +utilizar ``UnicodeDammit.detwingle()`` para transformar este documento em um +UTF-8 puro. Aqui está um exemplo:: + + snowmen = (u"\N{SNOWMAN}" * 3) + quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}") + doc = snowmen.encode("utf8") + quote.encode("windows_1252") + +Este documento é uma bagunça. O snowmen é um UTF-8 e as aspas são Windows-1252. +Você pode exibir o snowmen ou as aspas, mas não os dois ao mesmo tempo:: + + print(doc) + # ☃☃☃�I like snowmen!� + + print(doc.decode("windows-1252")) + # ☃☃☃“I like snowmen!” + +Decodificar um documento como UTF-8 gera um ``UnicodeDecodeError``, e +como um Windows-1252 lhe tras algo sem sentido. Felizmente, +``UnicodeDammit.detwingle()`` irá converter a string para UTF-8 puro, +permitindo a você decodificá-la para Unicode e exibir o snowmen e as +aspas simultaneamente:: + + new_doc = UnicodeDammit.detwingle(doc) + print(new_doc.decode("utf8")) + # ☃☃☃“I like snowmen!” + +``UnicodeDammit.detwingle()`` sabe apenas como trabalhar com Windows-1252 +contido em UTF-8 (ou vice versa, eu suponho), mas este é o caso mais comum. + +Note que você deve chamar ``UnicodeDammit.detwingle()`` em seu dado +antes de passá-lo para ``BeautifulSoup`` ou para o construtor ``UnicodeDammit``. +O Beautiful Soup assume que um documento possui apenas uma codificação, +independente de qual ela seja. Se você passar um documento que +contém ambos UTF-8 e Windows-1252, é provável que ele pense que todo +o documento seja Windows-1252, e o documento parecerá ``☃☃☃“I like snowmen!”``. + +``UnicodeDammit.detwingle()`` é novo no Beautiful Soup 4.1.0. + +Linhas numeradas +================ + +Os interpretadores ``html.parser` e ``html5lib`` podem rastrear onde, no +documento original, cada tag foi encontrada. Você pode acessar esta +informação através de ``Tag.sourceline`` (número da linha) e ``Tag.sourcepos`` +(posição do início da tag na linha):: + + markup = "Paragraph 1

\n

Paragraph 2

" + soup = BeautifulSoup(markup, 'html.parser') + for tag in soup.find_all('p'): + print(tag.sourceline, tag.sourcepos, tag.string) + # (1, 0, u'Paragraph 1') + # (2, 3, u'Paragraph 2') + +Note que os dois interpretadores significam coisas levemente diferentes por +``sourceline`` e ``sourcepos``. Para html.parser, estes números representam +a posição do sinal `menor que`inicial. Para html5lib, representa a posição +do sinal `maior que` final:: + + soup = BeautifulSoup(markup, 'html5lib') + for tag in soup.find_all('p'): + print(tag.sourceline, tag.sourcepos, tag.string) + # (2, 1, u'Paragraph 1') + # (3, 7, u'Paragraph 2') + +Você pode desabilitar esta característica passando ``store_line_numbers=False` +no construtor ``BeautifulSoup``:: + + markup = "Paragraph 1

\n

Paragraph 2

" + soup = BeautifulSoup(markup, 'html.parser', store_line_numbers=False) + soup.p.sourceline + # None + +Esta característica é nova no 4.8.1 e os analisadores baseados no lxml +não a suportam. + +Comparando objetos por igualdade +============================== + +O Beautiful Soup diz que dois objetos ``NavigableString`` ou ``Tag`` são +iguais quando eles apresentam as mesma marcação HTML ou XML. No exemplo +abaixo, as duas tags são tratadas como iguais, mesmo estando em partes +diferentes da árvore do objeto, porque ambas estão como "pizza":: + + markup = "

I want pizza and more pizza!

" + soup = BeautifulSoup(markup, 'html.parser') + first_b, second_b = soup.find_all('b') + print first_b == second_b + # True + + print first_b.previous_element == second_b.previous_element + # False + +Se você quiser verificar se duas variáveis se referem exatamente ao +mesmo objeto, use `is`:: + + print first_b is second_b + # False + +Copiando objetos Beautiful Soup +=============================== + +Você pode utilizar ``copy.copy()`` para criar uma cópia de qualquer ``Tag`` ou +``NavigableString``:: + + import copy + p_copy = copy.copy(soup.p) + print p_copy + #

I want pizza and more pizza!

+ + +A cópia será considerada igual ao original, desde que ela apresente a mesma +marcação que o original, mas não será o mesmo objeto:: + + print soup.p == p_copy + # True + + print soup.p is p_copy + # False + +A única diferença real é que a cópia é completamente separada da árvore +original do Beautiful Soup, como se ``extract()`` fosse chamado para ela:: + + print p_copy.parent + # None + +Isso acontece porque dois objetos ``Tag`` diferentes não podem ocupar o mesmo +espaço ao mesmo tempo. + + +Analisando apenas parte de um documento +======================================= + +Suponhamos que você queira que o Beautiful Soup olhe apenas para as +tags
de um documento. É um desperdício de tempo e memória analisar +todo o documento e, posteriormente, analisar novamente apenas para buscar +as tags . Seria muito mais rápido ignorar tudo o que não for em +primeiro lugar. A classe ``SoupStrainer`` permite que você escolha +qual partes do documento serão analisadas. Você deverá penas criar uma +instância de ``SoupStrainer`` e passá-la ao construtor ``BeautifulSoup`` +no argumento ``parse_only``. + +(Note que *esta característica não funcionará se você estiver utilizando +o html5lib*. Se você utilizar o html5lib, todo o documento será analisado. +Isso acontece porque html5lib constantemente reorganiza a árvore de análise +e se alguma parte do documento realmente não fizer parte dela, ela irá quebrar. +Para evitar confusão, no exemplo abaixo, forçarei o Beautiful Soup a usar o +analisador nativo do Python). + +``SoupStrainer`` +---------------- + +A classe ``SoupStrainer`` recebe os mesmos argumentos que qualquer método em `Buscando na árvore`_: :ref:`name `, :ref:`attrs +`, :ref:`string `, e :ref:`**kwargs `. Aqui temos três objetos ``SoupStrainer`` :: + + from bs4 import SoupStrainer + + only_a_tags = SoupStrainer("a") + + only_tags_with_id_link2 = SoupStrainer(id="link2") + + def is_short_string(string): + return len(string) < 10 + + only_short_strings = SoupStrainer(string=is_short_string) + +Irei trazer de volta o documento "three sisters" mais uma vez e veremos +como o documento se parece quando é analisado com estes três objetos ``SoupStrainer` +diferentes:: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify()) + # + # Elsie + # + # + # Lacie + # + # + # Tillie + # + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify()) + # + # Lacie + # + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify()) + # Elsie + # , + # Lacie + # and + # Tillie + # ... + # + +Você pode também passar um ``SoupStrainer`` em qualquer método coberto em `Buscando na árvore`_. +Este uso provavelmente não seja muito útil, mas pensei que deveria mencioná-lo:: + + soup = BeautifulSoup(html_doc) + soup.find_all(only_short_strings) + # [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie', + # u'\n\n', u'...', u'\n'] + +Solucionando Problemas +====================== + +.. _diagnose: + +``diagnose()`` +-------------- + +Se você está tendo problemas em entender o que o Beautiful Soup está +fazendo com um documento, passe o documento pela função ``diagnose()``. (Nova no Beautiful Soup 4.2.0.) +O Beautiful Soup irá retornar um relatório mostrando como diferentes parsers +lidam com o documento e irá lhe dizer o Beautiful Soup poderia estar utilizando outro parser:: + + from bs4.diagnose import diagnose + with open("bad.html") as fp: + data = fp.read() + diagnose(data) + + # Diagnostic running on Beautiful Soup 4.2.0 + # Python version 2.7.3 (default, Aug 1 2012, 05:16:07) + # I noticed that html5lib is not installed. Installing it may help. + # Found lxml version 2.3.2.0 + # + # Trying to parse your data with html.parser + # Here's what html.parser did with the document: + # ... + +Olhando para o que diagnose() retorna, poderá lhe dizer como resolver +o seu problema. Mesmo que não consiga, você poderá colar a saída de ``diagnose()`` +quando solicitar ajuda. + +Erros enquanto se analisa um documento +-------------------------------------- + +Existem dois tipos diferentes de erros de análise. Existem quebras +quando você passa para o Beautiful Soup um documento e ele retorna uma +exceção, geralmente um ``HTMLParser.HTMLParseError``. E existe o comportamento +inesperado, quando uma árvore de análise parece um pouco diferente do +documento usado para criá-la. + +Quase nenhum destes problemas são parte do Beautiful Soup. Não é +porque o Beautiful Soup é maravilhosamente um software bem escrito. É +porque o Beautiful Soup não inclui nenhum código de análise. Ao invés disso, +ele depende de analisadores externos. Se um analisador não funciona com +certo documento, a melhor solução é tentar um analisador diferente. Veja +`Instalando um analisador`_ para detalhes e uma comparação entre eles. + +Os erros de interpretação mais comuns são ``HTMLParser.HTMLParseError: + +malformed start tag`` e ``HTMLParser.HTMLParseError: bad end +tag``. Existem dois parsers gerados para o parser built in do Python +e a solução é :ref:`install lxml ou html5lib. ` + +Os tipos de erros de comportamento inesperado mais comuns acontecem +quando não é encontrada a tag buscada no documento. Você vê a busca +sendo executada, mas ``find_all()`` retorna ``[]`` ou ``find()`` retorna ``None``. +Este é um problema comum com o analisador HTML nativo do Python que algumas +vezes pula tags que ele não entende. Novamente, a solução é +:ref:`instalar o lxml ou html5lib.` + +Problemas de incompatibilidade de versões +----------------------------------------- + +* ``SyntaxError: Invalid syntax`` (on the line ``ROOT_TAG_NAME = + u'[document]'``): Causado por rodar a versão Python 2 do + Beautiful Soup no Python 3, sem converter o código. + +* ``ImportError: No module named HTMLParser`` - Causado por rodar a + versão Python 2 do Beautiful Soup no Python 3. + +* ``ImportError: No module named html.parser`` - Causado por rodar a + versão Python 3 do Beautiful Soup no Python 2. + +* ``ImportError: No module named BeautifulSoup`` - Causado por rodar + código do Beautiful Soup 3 em um sistema que não possui o BS3 + instalado. Ou por escrever código Beautiful Soup 4 sem saber que + o nome do pacote é diferente no ``bs4``. + +* ``ImportError: No module named bs4`` - Causado por rodar código Beautiful + Soup 4 em um sistema que não possui o BS4 instalado. + +.. _parsing-xml: + +Analisando um XML +----------------- + +Por padrão, o Beautiful Soup analisa documento como HTML. Para analisar um documento +como XML, passe "xml" como um segundo argumento ao construtor ``BeautifulSoup`` :: + + soup = BeautifulSoup(markup, "xml") + +Você precisará ter :ref:` lxml instalado `. + +Outros problemas com analisadores +--------------------------------- + +* Se seu script funciona em um computador, mas não em outro, + ou em um ambiente virtual mas não em outro, ou fora do ambiente + virtual mas não dentro dele, provavelmente porque ambos os ambientes + possuem bibliotecas de analisadores difererentes. Por exemplo, você pode + ter desenvolvido um script em um computador que possui lxml instalado, + e então estar tentando rodá-lo no seu computador que possui apenas html5lib + instalado. Veja :ref:`Diferenças entre os interpretadores (parsers)` para entender porque isso importa, + e corrija o problema mencionando uma biblioteca específica no construtor ``BeautifulSoup``. + +* Por tags `HTML e atributos serem case-insensitive + `_, todos os três + parsers HTML convertem tags e atributos para lowercase. Isso é, + a marcação é convertida para . Se você quiser + preservar a formatação anterior das tags e atributos, você precisará + :ref:`analisar o documento como XML. ` + +.. _misc: + +Diversos +-------- + +* ``UnicodeEncodeError: 'charmap' codec can't encode character + u'\xfoo' in position bar`` (ou qualquer outro + ``UnicodeEncodeError``) - Este não é um problema do Beautiful Soup. + Este problema poderá surgir em duas situações: a primeira quando você + tentar imprimir um caractere Unicode que seu console não sabe como + exibir. (Veja `Esta página na wiki do Python + `_ para saber mais.). A segunda, + quando você está gravando um arquivo e passa um caractere Unicode que + não é suportado pelo seu codificador padrão. Neste caso, a solução mais + simples é explicitamente converter a string Unicode em UTF-8 com + ``u.encode("utf8")``. + +* ``KeyError: [attr]`` - Caused by accessing ``tag['attr']`` quando a + tag em questão não define o atributo ``attr``. Os erros mais comuns são + ``KeyError: 'href'`` e ``KeyError: + 'class'``. Use ``tag.get('attr')`` se você não tem certeza se ``attr`` está + definido, assim como você faria em um dicionário Python. + +* ``AttributeError: 'ResultSet' object has no attribute 'foo'`` - Isso + geralmente ocorre quando você espera que ``find_all()`` retorne + uma única tag ou string. Mas ``find_all()`` retorn uma _lista_ de tags + e strings--um objeto ``ResultSet``. Você precisa iterar sobre a lista e + buscar ``.foo`` para cada um. Ou, se você realmente quiser apenas um resultado, + deverá usar ``find()`` ao invés de ``find_all()``. + +* ``AttributeError: 'NoneType' object has no attribute 'foo'`` - Isso + geralmente acontece quando é chamado ``find()`` e então se tenta acessar + o atributo `.foo`` o resultado. Mas no seu caso, ``find()`` não encontra nada, + então retorna ``None`` ao invés de retornar uma tag ou uma string. Você precisa + descobrir porque ``find()`` não está retornando nada. + +Melhorando a performance +------------------------ + +O Beautiful Soup nunca será tão rápido quanto os parsers em que +ele foi construido em cima. Se o tempo de resposta se tornar crítico, +se você estiver pagando por hora de uso de um computador ou se há +qualquer outra razão para que o tempo de processamento seja mais +valioso que o tempo de programação, você deve esquecer o Beautiful Soup +e trabalhar diretamente em cima do `lxml `_. + +Dito isso, existem algumas coisas que você pode fazer para acelerar o +Beautiful Soup. Se você não está utilizando o lxml como seu parser, +meu conselho é que o faça :ref:`start `. +O Beautiful Soup analisa documentos significativamente mais rápido +utilizando o lxml do que usando o html.parser ou html5lib. + +Você pode acelerar a detecção da codificação significativamente instalando +a biblioteca `cchardet `_ . + +`Analisando apenas parte do documento`_ não irá lhe poupar muito tempo de +análise, mas irá poupar muita memória e fará a `busca` no documento muito +mais rápida. + +Beautiful Soup 3 +================ + +O Beautiful Soup 3 é a versão anterior e não é mais desenvolvida +ativamente. Ela atualmente faz parte da maioria das distribuições +Linux: + +:kbd:`$ apt-get install python-beautifulsoup` + +Também está publicada no PyPi como ``BeautifulSoup``.: + +:kbd:`$ easy_install BeautifulSoup` + +:kbd:`$ pip install BeautifulSoup` + +Você também pode fazer o `download de um tarball do Beautiful Soup 3.2.0 +`_. + +Se você rodar ``easy_install beautifulsoup`` ou ``easy_install +BeautifulSoup``, mas seu código não funcionar, você instalou o Beautiful +Soup 3 por engano. Você precisa executar ``easy_install beautifulsoup4``. + +`A documentação do Beautiful Soup 3 está arquivada online +`_. + +Portabilidade de código para BS4 +-------------------------------- + +A maioria dos códigos escritos em Beautiful Soup 3 irá funcionar no +Beautiful Soup 4 com uma pequena alteração. Tudo que você precisa +fazer é alterar o nome do pacote de ``BeautifulSoup`` para ``bs4``. Então:: + + from BeautifulSoup import BeautifulSoup + +deverá ser assim:: + + from bs4 import BeautifulSoup + +* Se for gerado um ``ImportError`` "No module named BeautifulSoup", o + problema é que você está tentando executar um código Beautiful Soup 3, + mas possui apenas o Beautiful Soup 4 instalado. + +* Se for gerado um ``ImportError`` "No module named bs4", o problema + é que você está tentando executar um código Beautiful Soup 4, mas + possui apenas o Beautiful Soup 3 instalado. + +Apesar do BS4 ser quase totalmente compativel com BS3, a maioria de seus +métodos foram depreciados e renomeados para atender o padrão `PEP 8 +`_. Existem muitas outras +renomeações e alterações, e algumas delas quebram esta compatibilidade. + +Aqui está o que você irá precisar saber para converter seu código BS3 para BS4: + +Você precisa de um interpretador (parser) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +O Beautiful Soup 3 utilizava o ``SGMLParser`` do Python, um módulo que +foi depreciado e removido no Python 3.0. O Beautiful Soup 4 utiliza o +``html.parser`` por padrão, mas você pode adicionar o lxml ou html5lib +e utilizá-los como alternativa. Veja `Instalando um interpretador (parser)`_ para +comparação. + +Como o ``html.parser`` não é o mesmo analisador que ``SGMLParser``, é possível +que o Beautiful Soup 4 retorne uma árvore de análise diferente da +gerada pelo Beautiful Soup 3 para as mesmas marcações. Se você trocar +``html.parser`` por lxml ou html5lib, você poderá descorbrir que a árvore também +mudará. Se isso acontecer, você precisará atualizar seu código para lidar com a +nova árvore. + +Nomes dos Métodos +^^^^^^^^^^^^^^^^^ + +* ``renderContents`` -> ``encode_contents`` +* ``replaceWith`` -> ``replace_with`` +* ``replaceWithChildren`` -> ``unwrap`` +* ``findAll`` -> ``find_all`` +* ``findAllNext`` -> ``find_all_next`` +* ``findAllPrevious`` -> ``find_all_previous`` +* ``findNext`` -> ``find_next`` +* ``findNextSibling`` -> ``find_next_sibling`` +* ``findNextSiblings`` -> ``find_next_siblings`` +* ``findParent`` -> ``find_parent`` +* ``findParents`` -> ``find_parents`` +* ``findPrevious`` -> ``find_previous`` +* ``findPreviousSibling`` -> ``find_previous_sibling`` +* ``findPreviousSiblings`` -> ``find_previous_siblings`` +* ``getText`` -> ``get_text`` +* ``nextSibling`` -> ``next_sibling`` +* ``previousSibling`` -> ``previous_sibling`` + +Alguns argumentos do construtor do Beautiful Soup foram renomeados pelas +mesmas razões: + +* ``BeautifulSoup(parseOnlyThese=...)`` -> ``BeautifulSoup(parse_only=...)`` +* ``BeautifulSoup(fromEncoding=...)`` -> ``BeautifulSoup(from_encoding=...)`` + +Eu renomeei um método para compatibilidade com Python 3: + +* ``Tag.has_key()`` -> ``Tag.has_attr()`` + +Eu renomeei um atributo para utilizar uma terminologia mais precisa: + +* ``Tag.isSelfClosing`` -> ``Tag.is_empty_element`` + +Eu renomeei três atributos para evitar utilizar palavras reservadas do +Python. Ao contrário das outras, estas alterações *não são compativeis com +versões anteriores.* Se você utilizar estes atributos no BS3, seu código +irá quebrar no BS4 até você corrigí-los. + +* ``UnicodeDammit.unicode`` -> ``UnicodeDammit.unicode_markup`` +* ``Tag.next`` -> ``Tag.next_element`` +* ``Tag.previous`` -> ``Tag.previous_element`` + +Geradores +^^^^^^^^^ + +Eu dei nomes aos geradores de acordo com o PEP-8 e transformei-os +em propriedades: + +* ``childGenerator()`` -> ``children`` +* ``nextGenerator()`` -> ``next_elements`` +* ``nextSiblingGenerator()`` -> ``next_siblings`` +* ``previousGenerator()`` -> ``previous_elements`` +* ``previousSiblingGenerator()`` -> ``previous_siblings`` +* ``recursiveChildGenerator()`` -> ``descendants`` +* ``parentGenerator()`` -> ``parents`` + +Então, ao invés de:: + + for parent in tag.parentGenerator(): + ... + +Você pode escrever:: + + for parent in tag.parents: + ... + +(Mas a versão antiga ainda funcionará.) + +Alguns dos geradores eram utilizados para gerar ``None`` após +finalizado e então parar. Isso era um bug. Agora os geradores +apenas param. + +Existem dois novos geradores, :ref:`.strings e +.stripped_strings `. ``.strings`` gera objetos +NavigableString, e ``.stripped_strings`` gera strings Python com +espaços em branco removidos. + +XML +^^^ +Não existe mais uma classe ``BeautifulStoneSoup`` para analisar XML. Para +analisar XML você deverá passar "xml" como segundo argumento ao construtor +``BeautifulSoup``. Pela mesma razão, o construtor ``BeautifulSoup`` não +reconhece mais o argumento ``isHTML``. + +A manipulação do Beautiful Soup's de tags XML vazias foi melhorada. +Anteriormente, quando você analisava um XML, deveria explicitamente +dizer quais tags seriam consideradas elementos de tag vazios. O +argumento ``selfClosingTags`` não é mais reconhecido. Ao invés disso, +o Beautiful Soup considera qualquer tag vazia como um elemento de tag vazia. +Se você adicionar uma filha a um elemento de tag vazia, ela deixará de ser vazia. + +Entidades +^^^^^^^^^ + +Uma entidade HTML ou XML de entrada é sempre convertida em +seu caractere Unicode correspondente. O Beautiful Soup 3 possuia +inúmeras maneiras redundantes de lidar com entidades, as quais foram +removidas. O construtor ``BeautifulSoup`` não reconhece mais os argumentos +``smartQuotesTo`` ou ``convertEntities``. (`Unicode, +Dammit`_ ainda possui ``smart_quotes_to``, mas seu padrão agora é converter +smart quotes em Unicode.) As constantes ``HTML_ENTITIES``, +``XML_ENTITIES``, e ``XHTML_ENTITIES`` foram removidas, desde que elas +se referiam a uma feature (transformar algumas, mas não todas as entidades +em caracteres Unicode) que não existe mais. +Se você quiser transformar caracteres Unicode novamente em entidades HTML +na saída, ao invés de transformá-las em caracteres UTF-8, você precisará +utilizar um :ref:`output formatter `. + +Variados +^^^^^^^^ + +:ref:`Tag.string <.string>` agora opera recursivamente. Se a tag A +contém apenas uma tag B e nada mais, então A.string é o mesmo que +B.string. (Anteriormente era None) + +`Atributos com múltiplos valores`_ como ``class`` possuem listas de strings +como valores e não strings. Isso deverá afetar a maneira que você buscará +por classes CSS. + +Se você passar um dos métodos ``find*``, ambos :ref:`string ` `e` +um argumento específico de uma tag como :ref:`name `, o Beautiful Soup +irá buscar por tags que atentem o seu critério de argumento específico e que +:ref:`Tag.string <.string>` atenda o valor para :ref:`string `. Isso +`não` irá encontrar as strings por si. Anteriormente, Beautiful Soup ignorava +o argumento específico de uma tag e olhava apenas para as strings. + +O construtor ``BeautifulSoup`` não reconhece mais o argumento `markupMassage`. +É agora responsabilidade do parser de manipular a marcação corretamente. + +As classes raramente usadas do analisador como +``ICantBelieveItsBeautifulSoup`` e ``BeautifulSOAP`` foram removidas. +é agora decisão do analisador como manipular marcações ambiguas. + +O método ``prettify()`` agora retorna uma string Unicode, e não bytestring. diff --git a/doc.zh/source/6.1.jpg b/doc.zh/source/6.1.jpg new file mode 100644 index 0000000..97014f0 Binary files /dev/null and b/doc.zh/source/6.1.jpg differ diff --git a/doc.zh/source/index.rst b/doc.zh/source/index.rst new file mode 100644 index 0000000..03d2e05 --- /dev/null +++ b/doc.zh/source/index.rst @@ -0,0 +1,2739 @@ +.. BeautifulSoup文档 documentation master file, created by + Deron Wang on Fri Nov 29 13:49:30 2013. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Beautiful Soup 4.4.0 文档 +========================== + +`Beautiful Soup `_ 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间. + +这篇文档介绍了BeautifulSoup4中所有主要特性,并且有小例子.让我来向你展示它适合做什么,如何工作,怎样使用,如何达到你想要的效果,和处理异常情况. + +文档中出现的例子在Python2.7和Python3.2中的执行结果相同 + +你可能在寻找 `Beautiful Soup3 `_ 的文档,Beautiful Soup 3 目前已经停止开发,我们推荐在现在的项目中使用Beautiful Soup 4, `移植到BS4 `_ + +这篇帮助文档已经被翻译成了其它语言: + +* `这篇文档当然还有中文版. `_ +* このページは日本語で利用できます(`外部リンク `_) +* 이 문서는 한국어 번역도 가능합니다. (`외부 링크 `_) + + +寻求帮助 +-------- + +如果你有关于BeautifulSoup的问题,可以发送邮件到 `讨论组 `_ .如果你的问题包含了一段需要转换的HTML代码,那么确保你提的问题描述中附带这段HTML文档的 `代码诊断`_ [1]_ + +快速开始 +======== + +下面的一段HTML代码将作为例子被多次用到.这是 *爱丽丝梦游仙境的* 的一段内容(以后内容中简称为 *爱丽丝* 的文档): + +:: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + +使用BeautifulSoup解析这段代码,能够得到一个 ``BeautifulSoup`` 的对象,并能按照标准的缩进格式的结构输出: + +:: + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + + print(soup.prettify()) + # + # + # + # The Dormouse's story + # + # + # + #

+ # + # The Dormouse's story + # + #

+ #

+ # Once upon a time there were three little sisters; and their names were + # + # Elsie + # + # , + # + # Lacie + # + # and + # + # Tillie + # + # ; and they lived at the bottom of a well. + #

+ #

+ # ... + #

+ # + # + +几个简单的浏览结构化数据的方法: + +:: + + soup.title + # The Dormouse's story + + soup.title.name + # u'title' + + soup.title.string + # u'The Dormouse's story' + + soup.title.parent.name + # u'head' + + soup.p + #

The Dormouse's story

+ + soup.p['class'] + # u'title' + + soup.a + # Elsie + + soup.find_all('a') + # [Elsie, + # Lacie, + # Tillie] + + soup.find(id="link3") + # Tillie + +从文档中找到所有标签的链接: + +:: + + for link in soup.find_all('a'): + print(link.get('href')) + # http://example.com/elsie + # http://example.com/lacie + # http://example.com/tillie + +从文档中获取所有文字内容: + +:: + + print(soup.get_text()) + # The Dormouse's story + # + # The Dormouse's story + # + # Once upon a time there were three little sisters; and their names were + # Elsie, + # Lacie and + # Tillie; + # and they lived at the bottom of a well. + # + # ... + +这是你想要的吗?别着急,还有更好用的 + +安装 Beautiful Soup +====================== + +如果你用的是新版的Debain或ubuntu,那么可以通过系统的软件包管理来安装: + +``$ apt-get install Python-bs4`` + +Beautiful Soup 4 通过PyPi发布,所以如果你无法使用系统包管理安装,那么也可以通过 ``easy_install`` 或 ``pip`` 来安装.包的名字是 ``beautifulsoup4`` ,这个包兼容Python2和Python3. + +``$ easy_install beautifulsoup4`` + +``$ pip install beautifulsoup4`` + +(在PyPi中还有一个名字是 ``BeautifulSoup`` 的包,但那可能不是你想要的,那是 `Beautiful Soup3 `_ 的发布版本,因为很多项目还在使用BS3, 所以 ``BeautifulSoup`` 包依然有效.但是如果你在编写新项目,那么你应该安装的 ``beautifulsoup4`` ) + +如果你没有安装 ``easy_install`` 或 ``pip`` ,那你也可以 `下载BS4的源码 `_ ,然后通过setup.py来安装. + +``$ Python setup.py install`` + +如果上述安装方法都行不通,Beautiful Soup的发布协议允许你将BS4的代码打包在你的项目中,这样无须安装即可使用. + +作者在Python2.7和Python3.2的版本下开发Beautiful Soup, 理论上Beautiful Soup应该在所有当前的Python版本中正常工作 + +安装完成后的问题 +----------------- + +Beautiful Soup发布时打包成Python2版本的代码,在Python3环境下安装时,会自动转换成Python3的代码,如果没有一个安装的过程,那么代码就不会被转换. + +如果代码抛出了 ``ImportError`` 的异常: "No module named HTMLParser", 这是因为你在Python3版本中执行Python2版本的代码. + + +如果代码抛出了 ``ImportError`` 的异常: "No module named html.parser", 这是因为你在Python2版本中执行Python3版本的代码. + +如果遇到上述2种情况,最好的解决方法是重新安装BeautifulSoup4. + +如果在ROOT_TAG_NAME = u'[document]'代码处遇到 ``SyntaxError`` "Invalid syntax"错误,需要将把BS4的Python代码版本从Python2转换到Python3. 可以重新安装BS4: + +``$ Python3 setup.py install`` + +或在bs4的目录中执行Python代码版本转换脚本 + +``$ 2to3-3.2 -w bs4`` + +安装解析器 +------------ + +Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 `lxml `_ .根据操作系统不同,可以选择下列方法来安装lxml: + +``$ apt-get install Python-lxml`` + +``$ easy_install lxml`` + +``$ pip install lxml`` + +另一个可供选择的解析器是纯Python实现的 `html5lib `_ , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib: + +``$ apt-get install Python-html5lib`` + +``$ easy_install html5lib`` + +``$ pip install html5lib`` + +下表列出了主要的解析器,以及它们的优缺点: + ++-----------------------+---------------------------+---------------------------+---------------------------+ +| 解析器 | 使用方法 | 优势 | 劣势 | ++=======================+===========================+===========================+===========================+ +| Python标准库 | ``BeautifulSoup(markup, | - Python的内置标准库 | - Python 2.7.3 or 3.2.2)前| +| | "html.parser")`` | - 执行速度适中 | 的版本中文档容错能力差 | +| | | - 文档容错能力强 | | +| | | | | ++-----------------------+---------------------------+---------------------------+---------------------------+ +| lxml HTML 解析器 | ``BeautifulSoup(markup, | - 速度快 | - 需要安装C语言库 | +| | "lxml")`` | - 文档容错能力强 | | +| | | | | ++-----------------------+---------------------------+---------------------------+---------------------------+ +| lxml XML 解析器 | ``BeautifulSoup(markup, | - 速度快 | - 需要安装C语言库 | +| | ["lxml-xml"])`` | - 唯一支持XML的解析器 | | +| | | | | +| | ``BeautifulSoup(markup, | | | +| | "xml")`` | | | ++-----------------------+---------------------------+---------------------------+---------------------------+ +| html5lib | ``BeautifulSoup(markup, | - 最好的容错性 | - 速度慢 | +| | "html5lib")`` | - 以浏览器的方式解析文档 | - 不依赖外部扩展 | +| | | - 生成HTML5格式的文档 | | ++-----------------------+---------------------------+---------------------------+---------------------------+ + +推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定. + +提示: 如果一段HTML或XML文档格式不正确的话,那么在不同的解析器中返回的结果可能是不一样的,查看 `解析器之间的区别`_ 了解更多细节 + +如何使用 +======== + +将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄. + +:: + + from bs4 import BeautifulSoup + + soup = BeautifulSoup(open("index.html")) + + soup = BeautifulSoup("data") + +首先,文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码 + +:: + + BeautifulSoup("Sacré bleu!") + Sacré bleu! + +然后,Beautiful Soup选择最合适的解析器来解析这段文档,如果手动指定解析器那么Beautiful Soup会选择指定的解析器来解析文档.(参考 `解析成XML`_ ). + +对象的种类 +========== + +Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: +``Tag`` , ``NavigableString`` , ``BeautifulSoup`` , ``Comment`` . + +Tag +----- + +``Tag`` 对象与XML或HTML原生文档中的tag相同: + +:: + + soup = BeautifulSoup('Extremely bold') + tag = soup.b + type(tag) + # + +Tag有很多方法和属性,在 `遍历文档树`_ 和 `搜索文档树`_ 中有详细解释.现在介绍一下tag中最重要的属性: name和attributes + +Name +..... + +每个tag都有自己的名字,通过 ``.name`` 来获取: + +:: + + tag.name + # u'b' + +如果改变了tag的name,那将影响所有通过当前Beautiful Soup对象生成的HTML文档: + +:: + + tag.name = "blockquote" + tag + #
Extremely bold
+ +Attributes +............ + +一个tag可能有很多个属性. tag ```` 有一个 "class" 的属性,值为 "boldest" . tag的属性的操作方法与字典相同: + +:: + + tag['class'] + # u'boldest' + +也可以直接"点"取属性, 比如: ``.attrs`` : + +:: + + tag.attrs + # {u'class': u'boldest'} + +tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样 + +:: + + tag['class'] = 'verybold' + tag['id'] = 1 + tag + #
Extremely bold
+ + del tag['class'] + del tag['id'] + tag + #
Extremely bold
+ + tag['class'] + # KeyError: 'class' + print(tag.get('class')) + # None + +多值属性 +`````````` + +HTML 4定义了一系列可以包含多个值的属性.在HTML5中移除了一些,却增加更多.最常见的多值的属性是 class (一个tag可以有多个CSS的class). 还有一些属性 ``rel`` , ``rev`` , ``accept-charset`` , ``headers`` , ``accesskey`` . 在Beautiful Soup中多值属性的返回类型是list: + +:: + + css_soup = BeautifulSoup('

') + css_soup.p['class'] + # ["body", "strikeout"] + + css_soup = BeautifulSoup('

') + css_soup.p['class'] + # ["body"] + +如果某个属性看起来好像有多个值,但在任何版本的HTML定义中都没有被定义为多值属性,那么Beautiful Soup会将这个属性作为字符串返回 + +:: + + id_soup = BeautifulSoup('

') + id_soup.p['id'] + # 'my id' + +将tag转换成字符串时,多值属性会合并为一个值 + +:: + + rel_soup = BeautifulSoup('

Back to the homepage

') + rel_soup.a['rel'] + # ['index'] + rel_soup.a['rel'] = ['index', 'contents'] + print(rel_soup.p) + #

Back to the homepage

+ +如果转换的文档是XML格式,那么tag中不包含多值属性 + +:: + + xml_soup = BeautifulSoup('

', 'xml') + xml_soup.p['class'] + # u'body strikeout' + +可以遍历的字符串 +---------------- + +字符串常被包含在tag内.Beautiful Soup用 ``NavigableString`` 类来包装tag中的字符串: + +:: + + tag.string + # u'Extremely bold' + type(tag.string) + # + +一个 ``NavigableString`` 字符串与Python中的Unicode字符串相同,并且还支持包含在 `遍历文档树`_ 和 `搜索文档树`_ 中的一些特性. 通过 ``unicode()`` 方法可以直接将 ``NavigableString`` 对象转换成Unicode字符串: + +:: + + unicode_string = unicode(tag.string) + unicode_string + # u'Extremely bold' + type(unicode_string) + # + +tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用 `replace_with()`_ 方法: + +:: + + tag.string.replace_with("No longer bold") + tag + #
No longer bold
+ +``NavigableString`` 对象支持 `遍历文档树`_ 和 `搜索文档树`_ 中定义的大部分属性, 并非全部.尤其是,一个字符串不能包含其它内容(tag能够包含字符串或是其它tag),字符串不支持 ``.contents`` 或 ``.string`` 属性或 ``find()`` 方法. + +如果想在Beautiful Soup之外使用 ``NavigableString`` 对象,需要调用 ``unicode()`` 方法,将该对象转换成普通的Unicode字符串,否则就算Beautiful Soup已方法已经执行结束,该对象的输出也会带有对象的引用地址.这样会浪费内存. + +BeautifulSoup +---------------- + +``BeautifulSoup`` 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 ``Tag`` 对象,它支持 `遍历文档树`_ 和 `搜索文档树`_ 中描述的大部分的方法. + +因为 ``BeautifulSoup`` 对象并不是真正的HTML或XML的tag,所以它没有name和attribute属性.但有时查看它的 ``.name`` 属性是很方便的,所以 ``BeautifulSoup`` 对象包含了一个值为 "[document]" 的特殊属性 ``.name`` + +:: + + soup.name + # u'[document]' + +注释及特殊字符串 +----------------- + +``Tag`` , ``NavigableString`` , ``BeautifulSoup`` 几乎覆盖了html和xml中的所有内容,但是还有一些特殊对象.容易让人担心的内容是文档的注释部分: + +:: + + markup = "" + soup = BeautifulSoup(markup) + comment = soup.b.string + type(comment) + # + +``Comment`` 对象是一个特殊类型的 ``NavigableString`` 对象: + +:: + + comment + # u'Hey, buddy. Want to buy a used parser' + +但是当它出现在HTML文档中时, ``Comment`` 对象会使用特殊的格式输出: + +:: + + print(soup.b.prettify()) + # + # + # + +Beautiful Soup中定义的其它类型都可能会出现在XML的文档中: ``CData`` , ``ProcessingInstruction`` , ``Declaration`` , ``Doctype`` .与 ``Comment`` 对象类似,这些类都是 ``NavigableString`` 的子类,只是添加了一些额外的方法的字符串独享.下面是用CDATA来替代注释的例子: + +:: + + from bs4 import CData + cdata = CData("A CDATA block") + comment.replace_with(cdata) + + print(soup.b.prettify()) + # + # + # + +遍历文档树 +========== + +还拿"爱丽丝梦游仙境"的文档来做例子: + +:: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + +通过这段例子来演示怎样从文档的一段内容找到另一段内容 + +子节点 +------- + +一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性. + +注意: Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点 + +tag的名字 +.......... + +操作文档树最简单的方法就是告诉它你想获取的tag的name.如果想获取 标签,只要用 ``soup.head`` : + +:: + + soup.head + # The Dormouse's story + + soup.title + # The Dormouse's story + +这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取标签中的第一个标签: + +:: + + soup.body.b + # The Dormouse's story + +通过点取属性的方式只能获得当前名字的第一个tag: + +:: + + soup.a + # Elsie + +如果想要得到所有的标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 `Searching the tree` 中描述的方法,比如: find_all() + +:: + + soup.find_all('a') + # [Elsie, + # Lacie, + # Tillie] + +.contents 和 .children +........................ + +tag的 ``.contents`` 属性可以将tag的子节点以列表的方式输出: + +:: + + head_tag = soup.head + head_tag + # The Dormouse's story + + head_tag.contents + [The Dormouse's story] + + title_tag = head_tag.contents[0] + title_tag + # The Dormouse's story + title_tag.contents + # [u'The Dormouse's story'] + +``BeautifulSoup`` 对象本身一定会包含子节点,也就是说标签也是 ``BeautifulSoup`` 对象的子节点: + +:: + + len(soup.contents) + # 1 + soup.contents[0].name + # u'html' + +字符串没有 ``.contents`` 属性,因为字符串没有子节点: + +:: + + text = title_tag.contents[0] + text.contents + # AttributeError: 'NavigableString' object has no attribute 'contents' + +通过tag的 ``.children`` 生成器,可以对tag的子节点进行循环: + +:: + + for child in title_tag.children: + print(child) + # The Dormouse's story + +.descendants +.............. + +``.contents`` 和 ``.children`` 属性仅包含tag的直接子节点.例如,标签只有一个直接子节点 + +:: + + head_tag.contents + # [<title>The Dormouse's story] + +但是标签也包含一个子节点:字符串 “The Dormouse’s story”,这种情况下字符串 “The Dormouse’s story”也属于<head>标签的子孙节点. ``.descendants`` 属性可以对所有tag的子孙节点进行递归循环 [5]_ : + +:: + + for child in head_tag.descendants: + print(child) + # <title>The Dormouse's story + # The Dormouse's story + +上面的例子中, 标签只有一个子节点,但是有2个子孙节点:节点和的子节点, ``BeautifulSoup`` 有一个直接子节点(节点),却有很多子孙节点: + +:: + + len(list(soup.children)) + # 1 + len(list(soup.descendants)) + # 25 + +.string +........ + +如果tag只有一个 ``NavigableString`` 类型子节点,那么这个tag可以使用 ``.string`` 得到子节点: + +:: + + title_tag.string + # u'The Dormouse's story' + +如果一个tag仅有一个子节点,那么这个tag也可以使用 ``.string`` 方法,输出结果与当前唯一子节点的 ``.string`` 结果相同: + +:: + + head_tag.contents + # [The Dormouse's story] + + head_tag.string + # u'The Dormouse's story' + +如果tag包含了多个子节点,tag就无法确定 ``.string`` 方法应该调用哪个子节点的内容, ``.string`` 的输出结果是 ``None`` : + +:: + + print(soup.html.string) + # None + +.strings 和 stripped_strings +............................. + +如果tag中包含多个字符串 [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'...' + +全部是空格的行会被忽略掉,段首和段末的空白会被删除 + +父节点 +------- + +继续分析文档树,每个tag或字符串都有父节点:被包含在某个tag中 + +.parent +........ + +通过 ``.parent`` 属性来获取某个元素的父节点.在例子“爱丽丝”的文档中,标签是标签的父节点: + +:: + + title_tag = soup.title + title_tag + # <title>The Dormouse's story + title_tag.parent + # The Dormouse's story + +文档title的字符串也有父节点:标签 + +:: + + title_tag.string.parent + # <title>The Dormouse's story + +文档的顶层节点比如的父节点是 ``BeautifulSoup`` 对象: + +:: + + html_tag = soup.html + type(html_tag.parent) + # + +``BeautifulSoup`` 对象的 ``.parent`` 是None: + +:: + + print(soup.parent) + # None + +.parents +.......... + +通过元素的 ``.parents`` 属性可以递归得到元素的所有父辈节点,下面的例子使用了 ``.parents`` 方法遍历了标签到根节点的所有节点. + +:: + + link = soup.a + link + # Elsie + for parent in link.parents: + if parent is None: + print(parent) + else: + print(parent.name) + # p + # body + # html + # [document] + # None + +兄弟节点 +--------- + +看一段简单的例子: + +:: + + sibling_soup = BeautifulSoup("text1text2") + print(sibling_soup.prettify()) + # + # + # + # + # text1 + # + # + # text2 + # + # + # + # + +因为标签和标签是同一层:他们是同一个元素的子节点,所以可以被称为兄弟节点.一段文档以标准格式输出时,兄弟节点有相同的缩进级别.在代码中也可以使用这种关系. + +.next_sibling 和 .previous_sibling +.................................... + +在文档树中,使用 ``.next_sibling`` 和 ``.previous_sibling`` 属性来查询兄弟节点: + +:: + + sibling_soup.b.next_sibling + # text2 + + sibling_soup.c.previous_sibling + # text1 + +标签有 ``.next_sibling`` 属性,但是没有 ``.previous_sibling`` 属性,因为标签在同级节点中是第一个.同理,标签有 ``.previous_sibling`` 属性,却没有 ``.next_sibling`` 属性: + +:: + + print(sibling_soup.b.previous_sibling) + # None + print(sibling_soup.c.next_sibling) + # None + +例子中的字符串“text1”和“text2”不是兄弟节点,因为它们的父节点不同: + +:: + + sibling_soup.b.string + # u'text1' + + print(sibling_soup.b.string.next_sibling) + # None + +实际文档中的tag的 ``.next_sibling`` 和 ``.previous_sibling`` 属性通常是字符串或空白. 看看“爱丽丝”文档: + +:: + + Elsie + Lacie + Tillie + +如果以为第一个标签的 ``.next_sibling`` 结果是第二个标签,那就错了,真实结果是第一个标签和第二个标签之间的顿号和换行符: + +:: + + link = soup.a + link + # Elsie + + link.next_sibling + # u',\n' + +第二个标签是顿号的 ``.next_sibling`` 属性: + +:: + + link.next_sibling.next_sibling + # Lacie + +.next_siblings 和 .previous_siblings +...................................... + +通过 ``.next_siblings`` 和 ``.previous_siblings`` 属性可以对当前节点的兄弟节点迭代输出: + +:: + + for sibling in soup.a.next_siblings: + print(repr(sibling)) + # u',\n' + # Lacie + # u' and\n' + # Tillie + # u'; and they lived at the bottom of a well.' + # None + + for sibling in soup.find(id="link3").previous_siblings: + print(repr(sibling)) + # ' and\n' + # Lacie + # u',\n' + # Elsie + # u'Once upon a time there were three little sisters; and their names were\n' + # None + +回退和前进 +---------- + +看一下“爱丽丝” 文档: + +:: + + The Dormouse's story +

The Dormouse's story

+ +HTML解析器把这段字符串转换成一连串的事件: "打开标签","打开一个标签","打开一个标签","添加一段字符串","关闭<title>标签","打开<p>标签",等等.Beautiful Soup提供了重现解析器初始化过程的方法. + +.next_element 和 .previous_element +................................... + +``.next_element`` 属性指向解析过程中下一个被解析的对象(字符串或tag),结果可能与 ``.next_sibling`` 相同,但通常是不一样的. + +这是“爱丽丝”文档中最后一个<a>标签,它的 ``.next_sibling`` 结果是一个字符串,因为当前的解析过程 [2]_ 因为当前的解析过程因为遇到了<a>标签而中断了: + +:: + + last_a_tag = soup.find("a", id="link3") + last_a_tag + # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> + + last_a_tag.next_sibling + # '; and they lived at the bottom of a well.' + +但这个<a>标签的 ``.next_element`` 属性结果是在<a>标签被解析之后的解析内容,不是<a>标签后的句子部分,应该是字符串"Tillie": + +:: + + last_a_tag.next_element + # u'Tillie' + +这是因为在原始文档中,字符串“Tillie” 在分号前出现,解析器先进入<a>标签,然后是字符串“Tillie”,然后关闭</a>标签,然后是分号和剩余部分.分号与<a>标签在同一层级,但是字符串“Tillie”会被先解析. + +``.previous_element`` 属性刚好与 ``.next_element`` 相反,它指向当前被解析的对象的前一个解析对象: + +:: + + last_a_tag.previous_element + # u' and\n' + last_a_tag.previous_element.next_element + # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> + +.next_elements 和 .previous_elements +..................................... + +通过 ``.next_elements`` 和 ``.previous_elements`` 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样: + +:: + + for element in last_a_tag.next_elements: + print(repr(element)) + # u'Tillie' + # u';\nand they lived at the bottom of a well.' + # u'\n\n' + # <p class="story">...</p> + # u'...' + # u'\n' + # None + +搜索文档树 +========== + +Beautiful Soup定义了很多搜索方法,这里着重介绍2个: ``find()`` 和 ``find_all()`` .其它方法的参数和用法类似,请读者举一反三. + +再以“爱丽丝”文档作为例子: + +:: + + html_doc = """ + <html><head><title>The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + from bs4 import BeautifulSoup + soup = BeautifulSoup(html_doc, 'html.parser') + +使用 ``find_all()`` 类似的方法可以查找到想要查找的文档内容 + +过滤器 +------ + +介绍 ``find_all()`` 方法前,先介绍一下过滤器的类型 [3]_ ,这些过滤器贯穿整个搜索的API.过滤器可以被用在tag的name中,节点的属性中,字符串中或他们的混合中. + +字符串 +............ + +最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签: + +:: + + soup.find_all('b') + # [The Dormouse's story] + +如果传入字节码参数,Beautiful Soup会当作UTF-8编码,可以传入一段Unicode 编码来避免Beautiful Soup解析编码出错 + +正则表达式 +.......... + +如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 ``match()`` 来匹配内容.下面例子中找出所有以b开头的标签,这表示和标签都应该被找到: + +:: + + import re + for tag in soup.find_all(re.compile("^b")): + print(tag.name) + # body + # b + +下面代码找出所有名字中包含"t"的标签: + +:: + + for tag in soup.find_all(re.compile("t")): + print(tag.name) + # html + # title + +列表 +.... + +如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有标签和标签: + +:: + + soup.find_all(["a", "b"]) + # [The Dormouse's story, + # Elsie, + # Lacie, + # Tillie] + +True +..... + +``True`` 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点 + +:: + + for tag in soup.find_all(True): + print(tag.name) + # html + # head + # title + # body + # p + # b + # p + # a + # a + # a + # p + +方法 +.... + +如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4]_ ,如果这个方法返回 ``True`` 表示当前元素匹配并且被找到,如果不是则反回 ``False`` + +下面方法校验了当前元素,如果包含 ``class`` 属性却不包含 ``id`` 属性,那么将返回 ``True``: + +:: + + def has_class_but_no_id(tag): + return tag.has_attr('class') and not tag.has_attr('id') + +将这个方法作为参数传入 ``find_all()`` 方法,将得到所有

标签: + +:: + + soup.find_all(has_class_but_no_id) + # [

The Dormouse's story

, + #

Once upon a time there were...

, + #

...

] + +返回结果中只有

标签没有标签,因为标签还定义了"id",没有返回和,因为和中没有定义"class"属性. + +通过一个方法来过滤一类标签属性的时候, 这个方法的参数是要被过滤的属性的值, 而不是这个标签. +下面的例子是找出 ``href`` 属性不符合指定正则的 ``a`` 标签. + +:: + + + def not_lacie(href): + return href and not re.compile("lacie").search(href) + soup.find_all(href=not_lacie) + # [Elsie, + # Tillie] + +标签过滤方法可以使用复杂方法. 下面的例子可以过滤出前后都有文字的标签. + +:: + + from bs4 import NavigableString + def surrounded_by_strings(tag): + return (isinstance(tag.next_element, NavigableString) + and isinstance(tag.previous_element, NavigableString)) + + for tag in soup.find_all(surrounded_by_strings): + print tag.name + # p + # a + # a + # a + # p + +现在来了解一下搜索方法的细节 + +find_all() +----------- + +find_all( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +``find_all()`` 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件.这里有几个例子: + +:: + + soup.find_all("title") + # [The Dormouse's story] + + soup.find_all("p", "title") + # [

The Dormouse's story

] + + soup.find_all("a") + # [Elsie, + # Lacie, + # Tillie] + + soup.find_all(id="link2") + # [Lacie] + + import re + soup.find(string=re.compile("sisters")) + # u'Once upon a time there were three little sisters; and their names were\n' + +有几个方法很相似,还有几个方法是新的,参数中的 ``string`` 和 ``id`` 是什么含义? 为什么 ``find_all("p", "title")`` 返回的是CSS Class为"title"的

标签? 我们来仔细看一下 ``find_all()`` 的参数 + +name 参数 +.......... + +``name`` 参数可以查找所有名字为 ``name`` 的tag,字符串对象会被自动忽略掉. + +简单的用法如下: + +:: + + soup.find_all("title") + # [The Dormouse's story] + +重申: 搜索 ``name`` 参数的值可以使任一类型的 `过滤器`_ ,字符窜,正则表达式,列表,方法或是 ``True`` . + +keyword 参数 +.............. + +如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 ``id`` 的参数,Beautiful Soup会搜索每个tag的"id"属性. + +:: + + soup.find_all(id='link2') + # [Lacie] + +如果传入 ``href`` 参数,Beautiful Soup会搜索每个tag的"href"属性: + +:: + + soup.find_all(href=re.compile("elsie")) + # [Elsie] + +搜索指定名字的属性时可以使用的参数值包括 `字符串`_ , `正则表达式`_ , `列表`_, `True`_ . + +下面的例子在文档树中查找所有包含 ``id`` 属性的tag,无论 ``id`` 的值是什么: + +:: + + soup.find_all(id=True) + # [Elsie, + # Lacie, + # Tillie] + +使用多个指定名字的参数可以同时过滤tag的多个属性: + +:: + + soup.find_all(href=re.compile("elsie"), id='link1') + # [three] + +有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性: + +:: + + data_soup = BeautifulSoup('

foo!
') + data_soup.find_all(data-foo="value") + # SyntaxError: keyword can't be an expression + +但是可以通过 ``find_all()`` 方法的 ``attrs`` 参数定义一个字典参数来搜索包含特殊属性的tag: + +:: + + data_soup.find_all(attrs={"data-foo": "value"}) + # [
foo!
] + +按CSS搜索 +.......... + +按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 ``class`` 在Python中是保留字,使用 ``class`` 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 ``class_`` 参数搜索有指定CSS类名的tag: + +:: + + soup.find_all("a", class_="sister") + # [Elsie, + # Lacie, + # Tillie] + +``class_`` 参数同样接受不同类型的 ``过滤器`` ,字符串,正则表达式,方法或 ``True`` : + +:: + + soup.find_all(class_=re.compile("itl")) + # [

The Dormouse's story

] + + def has_six_characters(css_class): + return css_class is not None and len(css_class) == 6 + + soup.find_all(class_=has_six_characters) + # [Elsie, + # Lacie, + # Tillie] + +tag的 ``class`` 属性是 `多值属性`_ .按照CSS类名搜索tag时,可以分别搜索tag中的每个CSS类名: + +:: + + css_soup = BeautifulSoup('

') + css_soup.find_all("p", class_="strikeout") + # [

] + + css_soup.find_all("p", class_="body") + # [

] + +搜索 ``class`` 属性时也可以通过CSS值完全匹配: + +:: + + css_soup.find_all("p", class_="body strikeout") + # [

] + +完全匹配 ``class`` 的值时,如果CSS类名的顺序与实际不符,将搜索不到结果: + +:: + + soup.find_all("a", attrs={"class": "sister"}) + # [Elsie, + # Lacie, + # Tillie] + +``string`` 参数 +............... + +通过 ``string`` 参数可以搜搜文档中的字符串内容.与 ``name`` 参数的可选值一样, ``string`` 参数接受 `字符串`_ , `正则表达式`_ , `列表`_, `True`_ . 看例子: + +:: + + soup.find_all(string="Elsie") + # [u'Elsie'] + + soup.find_all(string=["Tillie", "Elsie", "Lacie"]) + # [u'Elsie', u'Lacie', u'Tillie'] + + soup.find_all(string=re.compile("Dormouse")) + [u"The Dormouse's story", u"The Dormouse's story"] + + def is_the_only_string_within_a_tag(s): + ""Return True if this string is the only child of its parent tag."" + return (s == s.parent.string) + + soup.find_all(string=is_the_only_string_within_a_tag) + # [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...'] + +虽然 ``string`` 参数用于搜索字符串,还可以与其它参数混合使用来过滤tag.Beautiful Soup会找到 ``.string`` 方法与 ``string`` 参数值相符的tag.下面代码用来搜索内容里面包含“Elsie”的标签: + +:: + + soup.find_all("a", string="Elsie") + # [Elsie] + +``limit`` 参数 +............... + +``find_all()`` 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 ``limit`` 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 ``limit`` 的限制时,就停止搜索返回结果. + +文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量: + +:: + + soup.find_all("a", limit=2) + # [Elsie, + # Lacie] + +``recursive`` 参数 +................... + +调用tag的 ``find_all()`` 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 ``recursive=False`` . + +一段简单的文档: + +:: + + + + + The Dormouse's story + + + ... + +是否使用 ``recursive`` 参数的搜索结果: + +:: + + soup.html.find_all("title") + # [The Dormouse's story] + + soup.html.find_all("title", recursive=False) + # [] + +这是文档片段 + +:: + + + + + The Dormouse's story + + + ... + +标签在 <html> 标签下, 但并不是直接子节点, <head> 标签才是直接子节点. +在允许查询所有后代节点时 Beautiful Soup 能够查找到 <title> 标签. +但是使用了 ``recursive=False`` 参数之后,只能查找直接子节点,这样就查不到 <title> 标签了. + +Beautiful Soup 提供了多种DOM树搜索方法. 这些方法都使用了类似的参数定义. +比如这些方法: ``find_all()``: ``name``, ``attrs``, ``text``, ``limit``. +但是只有 ``find_all()`` 和 ``find()`` 支持 ``recursive`` 参数. + +像调用 ``find_all()`` 一样调用tag +---------------------------------- + +``find_all()`` 几乎是Beautiful Soup中最常用的搜索方法,所以我们定义了它的简写方法. ``BeautifulSoup`` 对象和 ``tag`` 对象可以被当作一个方法来使用,这个方法的执行结果与调用这个对象的 ``find_all()`` 方法相同,下面两行代码是等价的: + +:: + + soup.find_all("a") + soup("a") + +这两行代码也是等价的: + +:: + + soup.title.find_all(string=True) + soup.title(string=True) + +find() +------- + +find( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +``find_all()`` 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个<body>标签,那么使用 ``find_all()`` 方法来查找<body>标签就不太合适, 使用 ``find_all`` 方法并设置 ``limit=1`` 参数不如直接使用 ``find()`` 方法.下面两行代码是等价的: + +:: + + soup.find_all('title', limit=1) + # [<title>The Dormouse's story] + + soup.find('title') + # The Dormouse's story + +唯一的区别是 ``find_all()`` 方法的返回结果是值包含一个元素的列表,而 ``find()`` 方法直接返回结果. + +``find_all()`` 方法没有找到目标是返回空列表, ``find()`` 方法找不到目标时,返回 ``None`` . + +:: + + print(soup.find("nosuchtag")) + # None + +``soup.head.title`` 是 `tag的名字`_ 方法的简写.这个简写的原理就是多次调用当前tag的 ``find()`` 方法: + +:: + + soup.head.title + # The Dormouse's story + + soup.find("head").find("title") + # The Dormouse's story + +find_parents() 和 find_parent() +-------------------------------- + +find_parents( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +find_parent( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +我们已经用了很大篇幅来介绍 ``find_all()`` 和 ``find()`` 方法,Beautiful Soup中还有10个用于搜索的API.它们中的五个用的是与 ``find_all()`` 相同的搜索参数,另外5个与 ``find()`` 方法的搜索参数类似.区别仅是它们搜索文档的不同部分. + +记住: ``find_all()`` 和 ``find()`` 只搜索当前节点的所有子节点,孙子节点等. ``find_parents()`` 和 ``find_parent()`` 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档\搜索文档包含的内容. 我们从一个文档中的一个叶子节点开始: + +:: + + a_string = soup.find(string="Lacie") + a_string + # u'Lacie' + + a_string.find_parents("a") + # [Lacie] + + a_string.find_parent("p") + #

Once upon a time there were three little sisters; and their names were + # Elsie, + # Lacie and + # Tillie; + # and they lived at the bottom of a well.

+ + a_string.find_parents("p", class="title") + # [] + +文档中的一个标签是是当前叶子节点的直接父节点,所以可以被找到.还有一个

标签,是目标叶子节点的间接父辈节点,所以也可以被找到.包含class值为"title"的

标签不是不是目标叶子节点的父辈节点,所以通过 ``find_parents()`` 方法搜索不到. + +``find_parent()`` 和 ``find_parents()`` 方法会让人联想到 `.parent`_ 和 `.parents`_ 属性.它们之间的联系非常紧密.搜索父辈节点的方法实际上就是对 ``.parents`` 属性的迭代搜索. + +find_next_siblings() 和 find_next_sibling() +------------------------------------------- + +find_next_siblings( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +find_next_sibling( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +这2个方法通过 `.next_siblings`_ 属性对当tag的所有后面解析 [5]_ 的兄弟tag节点进行迭代, ``find_next_siblings()`` 方法返回所有符合条件的后面的兄弟节点, ``find_next_sibling()`` 只返回符合条件的后面的第一个tag节点. + +:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_next_siblings("a") + # [Lacie, + # Tillie] + + first_story_paragraph = soup.find("p", "story") + first_story_paragraph.find_next_sibling("p") + #

...

+ +find_previous_siblings() 和 find_previous_sibling() +----------------------------------------------------- + +find_previous_siblings( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +find_previous_sibling( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +这2个方法通过 `.previous_siblings`_ 属性对当前tag的前面解析 [5]_ 的兄弟tag节点进行迭代, ``find_previous_siblings()`` 方法返回所有符合条件的前面的兄弟节点, ``find_previous_sibling()`` 方法返回第一个符合条件的前面的兄弟节点: + +:: + + last_link = soup.find("a", id="link3") + last_link + # Tillie + + last_link.find_previous_siblings("a") + # [Lacie, + # Elsie] + + first_story_paragraph = soup.find("p", "story") + first_story_paragraph.find_previous_sibling("p") + #

The Dormouse's story

+ +find_all_next() 和 find_next() +-------------------------------- + +find_all_next( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +find_next( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +这2个方法通过 `.next_elements`_ 属性对当前tag的之后的 [5]_ tag和字符串进行迭代, ``find_all_next()`` 方法返回所有符合条件的节点, ``find_next()`` 方法返回第一个符合条件的节点: + +:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_all_next(string=True) + # [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'] + + first_link.find_next("p") + #

...

+ +第一个例子中,字符串 “Elsie”也被显示出来,尽管它被包含在我们开始查找的标签的里面.第二个例子中,最后一个

标签也被显示出来,尽管它与我们开始查找位置的标签不属于同一部分.例子中,搜索的重点是要匹配过滤器的条件,并且在文档中出现的顺序而不是开始查找的元素的位置. + +find_all_previous() 和 find_previous() +--------------------------------------- + +find_all_previous( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +find_previous( `name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ ) + +这2个方法通过 `.previous_elements`_ 属性对当前节点前面 [5]_ 的tag和字符串进行迭代, ``find_all_previous()`` 方法返回所有符合条件的节点, ``find_previous()`` 方法返回第一个符合条件的节点. + +:: + + first_link = soup.a + first_link + # Elsie + + first_link.find_all_previous("p") + # [

Once upon a time there were three little sisters; ...

, + #

The Dormouse's story

] + + first_link.find_previous("title") + # The Dormouse's story + +``find_all_previous("p")`` 返回了文档中的第一段(class="title"的那段),但还返回了第二段,

标签包含了我们开始查找的标签.不要惊讶,这段代码的功能是查找所有出现在指定标签之前的

标签,因为这个

标签包含了开始的标签,所以

标签一定是在之前出现的. + +CSS选择器 +------------ + +Beautiful Soup支持大部分的CSS选择器 ``_ [6]_ , +在 ``Tag`` 或 ``BeautifulSoup`` 对象的 ``.select()`` 方法中传入字符串参数, +即可使用CSS选择器的语法找到tag: + +:: + + soup.select("title") + # [The Dormouse's story] + + soup.select("p:nth-of-type(3)") + # [

...

] + +通过tag标签逐层查找: + +:: + + soup.select("body a") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("html head title") + # [The Dormouse's story] + +找到某个tag标签下的直接子标签 [6]_ : + +:: + + soup.select("head > title") + # [The Dormouse's story] + + soup.select("p > a") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("p > a:nth-of-type(2)") + # [Lacie] + + soup.select("p > #link1") + # [Elsie] + + soup.select("body > a") + # [] + +找到兄弟节点标签: + +:: + + soup.select("#link1 ~ .sister") + # [Lacie, + # Tillie] + + soup.select("#link1 + .sister") + # [Lacie] + +通过CSS的类名查找: + +:: + + soup.select(".sister") + # [Elsie, + # Lacie, + # Tillie] + + soup.select("[class~=sister]") + # [Elsie, + # Lacie, + # Tillie] + +通过tag的id查找: + +:: + + soup.select("#link1") + # [Elsie] + + soup.select("a#link2") + # [Lacie] + +同时用多种CSS选择器查询元素: + +:: + + soup.select("#link1,#link2") + # [Elsie, + # Lacie] + + +通过是否存在某个属性来查找: + +:: + + soup.select('a[href]') + # [Elsie, + # Lacie, + # Tillie] + +通过属性的值来查找: + +:: + + soup.select('a[href="http://example.com/elsie"]') + # [Elsie] + + soup.select('a[href^="http://example.com/"]') + # [Elsie, + # Lacie, + # Tillie] + + soup.select('a[href$="tillie"]') + # [Tillie] + + soup.select('a[href*=".com/el"]') + # [Elsie] + +通过语言设置来查找: + +:: + + multilingual_markup = """ +

Hello

+

Howdy, y'all

+

Pip-pip, old fruit

+

Bonjour mes amis

+ """ + multilingual_soup = BeautifulSoup(multilingual_markup) + multilingual_soup.select('p[lang|=en]') + # [

Hello

, + #

Howdy, y'all

, + #

Pip-pip, old fruit

] + +返回查找到的元素的第一个 + +:: + + soup.select_one(".sister") + # Elsie + + +对于熟悉CSS选择器语法的人来说这是个非常方便的方法.Beautiful Soup也支持CSS选择器API, +如果你仅仅需要CSS选择器的功能,那么直接使用 ``lxml`` 也可以, +而且速度更快,支持更多的CSS选择器语法,但Beautiful Soup整合了CSS选择器的语法和自身方便使用API. + + +修改文档树 +=========== + +Beautiful Soup的强项是文档树的搜索,但同时也可以方便的修改文档树 + +修改tag的名称和属性 +------------------- + +在 `Attributes`_ 的章节中已经介绍过这个功能,但是再看一遍也无妨. 重命名一个tag,改变属性的值,添加或删除属性: + +:: + + soup = BeautifulSoup('Extremely bold') + tag = soup.b + + tag.name = "blockquote" + tag['class'] = 'verybold' + tag['id'] = 1 + tag + #
Extremely bold
+ + del tag['class'] + del tag['id'] + tag + #
Extremely bold
+ +修改 .string +------------- + +给tag的 ``.string`` 属性赋值,就相当于用当前的内容替代了原来的内容: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + + tag = soup.a + tag.string = "New link text." + tag + # New link text. + +注意: 如果当前的tag包含了其它tag,那么给它的 ``.string`` 属性赋值会覆盖掉原有的所有内容包括子tag + +append() +---------- + +``Tag.append()`` 方法想tag中添加内容,就好像Python的列表的 ``.append()`` 方法: + +:: + + soup = BeautifulSoup("Foo") + soup.a.append("Bar") + + soup + # FooBar + soup.a.contents + # [u'Foo', u'Bar'] + +NavigableString() 和 .new_tag() +----------------------------------------- + +如果想添加一段文本内容到文档中也没问题,可以调用Python的 ``append()`` 方法 +或调用 ``NavigableString`` 的构造方法: + +:: + + soup = BeautifulSoup("") + tag = soup.b + tag.append("Hello") + new_string = NavigableString(" there") + tag.append(new_string) + tag + # Hello there. + tag.contents + # [u'Hello', u' there'] + +如果想要创建一段注释,或 ``NavigableString`` 的任何子类, 只要调用 NavigableString 的构造方法: + +:: + + from bs4 import Comment + new_comment = soup.new_string("Nice to see you.", Comment) + tag.append(new_comment) + tag + # Hello there + tag.contents + # [u'Hello', u' there', u'Nice to see you.'] + +# 这是Beautiful Soup 4.2.1 中新增的方法 + +创建一个tag最好的方法是调用工厂方法 ``BeautifulSoup.new_tag()`` : + +:: + + soup = BeautifulSoup("") + original_tag = soup.b + + new_tag = soup.new_tag("a", href="http://www.example.com") + original_tag.append(new_tag) + original_tag + # + + new_tag.string = "Link text." + original_tag + # Link text. + +第一个参数作为tag的name,是必填,其它参数选填 + +insert() +-------- + +``Tag.insert()`` 方法与 ``Tag.append()`` 方法类似,区别是不会把新元素添加到父节点 ``.contents`` 属性的最后,而是把元素插入到指定的位置.与Python列表总的 ``.insert()`` 方法的用法下同: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + tag = soup.a + + tag.insert(1, "but did not endorse ") + tag + # I linked to but did not endorse example.com + tag.contents + # [u'I linked to ', u'but did not endorse', example.com] + +insert_before() 和 insert_after() +----------------------------------- + +``insert_before()`` 方法在当前tag或文本节点前插入内容: + +:: + + soup = BeautifulSoup("stop") + tag = soup.new_tag("i") + tag.string = "Don't" + soup.b.string.insert_before(tag) + soup.b + # Don'tstop + +``insert_after()`` 方法在当前tag或文本节点后插入内容: + +:: + + soup.b.i.insert_after(soup.new_string(" ever ")) + soup.b + # Don't ever stop + soup.b.contents + # [Don't, u' ever ', u'stop'] + +clear() +-------- + +``Tag.clear()`` 方法移除当前tag的内容: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + tag = soup.a + + tag.clear() + tag + # + +extract() +---------- + +``PageElement.extract()`` 方法将当前tag移除文档树,并作为方法结果返回: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + i_tag = soup.i.extract() + + a_tag + # I linked to + + i_tag + # example.com + + print(i_tag.parent) + None + +这个方法实际上产生了2个文档树: 一个是用来解析原始文档的 ``BeautifulSoup`` 对象,另一个是被移除并且返回的tag.被移除并返回的tag可以继续调用 ``extract`` 方法: + +:: + + my_string = i_tag.string.extract() + my_string + # u'example.com' + + print(my_string.parent) + # None + i_tag + # + +decompose() +------------ + +``Tag.decompose()`` 方法将当前节点移除文档树并完全销毁: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + soup.i.decompose() + + a_tag + # I linked to + +replace_with() +--------------- + +``PageElement.replace_with()`` 方法移除文档树中的某段内容,并用新tag或文本节点替代它: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + new_tag = soup.new_tag("b") + new_tag.string = "example.net" + a_tag.i.replace_with(new_tag) + + a_tag + # I linked to example.net + +``replace_with()`` 方法返回被替代的tag或文本节点,可以用来浏览或添加到文档树其它地方 + +wrap() +------ + +``PageElement.wrap()`` 方法可以对指定的tag元素进行包装 [8]_ ,并返回包装后的结果: + +:: + + soup = BeautifulSoup("

I wish I was bold.

") + soup.p.string.wrap(soup.new_tag("b")) + # I wish I was bold. + + soup.p.wrap(soup.new_tag("div")) + #

I wish I was bold.

+ +该方法在 Beautiful Soup 4.0.5 中添加 + +unwrap() +--------- + +``Tag.unwrap()`` 方法与 ``wrap()`` 方法相反.将移除tag内的所有tag标签,该方法常被用来进行标记的解包: + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + a_tag = soup.a + + a_tag.i.unwrap() + a_tag + # I linked to example.com + +与 ``replace_with()`` 方法相同, ``unwrap()`` 方法返回被移除的tag + +输出 +==== + +格式化输出 +----------- + +``prettify()`` 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行 + +:: + + markup = 'I linked to example.com' + soup = BeautifulSoup(markup) + soup.prettify() + # '\n \n \n \n \n...' + + print(soup.prettify()) + # + # + # + # + # + # I linked to + # + # example.com + # + # + # + # + +``BeautifulSoup`` 对象和它的tag节点都可以调用 ``prettify()`` 方法: + +:: + + print(soup.a.prettify()) + # + # I linked to + # + # example.com + # + # + +压缩输出 +---------- + +如果只想得到结果字符串,不重视格式,那么可以对一个 ``BeautifulSoup`` 对象或 ``Tag`` 对象使用Python的 ``unicode()`` 或 ``str()`` 方法: + +:: + + str(soup) + # 'I linked to example.com' + + unicode(soup.a) + # u'I linked to example.com' + +``str()`` 方法返回UTF-8编码的字符串,可以指定 `编码`_ 的设置. + +还可以调用 ``encode()`` 方法获得字节码或调用 ``decode()`` 方法获得Unicode. + +输出格式 +--------- + +Beautiful Soup输出是会将HTML中的特殊字符转换成Unicode,比如“&lquot;”: + +:: + + soup = BeautifulSoup("“Dammit!” he said.") + unicode(soup) + # u'\u201cDammit!\u201d he said.' + +如果将文档转换成字符串,Unicode编码会被编码成UTF-8.这样就无法正确显示HTML特殊字符了: + +:: + + str(soup) + # '\xe2\x80\x9cDammit!\xe2\x80\x9d he said.' + +get_text() +---------- + +如果只想得到tag中包含的文本内容,那么可以调用 ``get_text()`` 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回: + +:: + + markup = '\nI linked to example.com\n' + soup = BeautifulSoup(markup) + + soup.get_text() + u'\nI linked to example.com\n' + soup.i.get_text() + u'example.com' + +可以通过参数指定tag的文本内容的分隔符: + +:: + + # soup.get_text("|") + u'\nI linked to |example.com|\n' + +还可以去除获得文本内容的前后空白: + +:: + + # soup.get_text("|", strip=True) + u'I linked to|example.com' + +或者使用 `.stripped_strings`_ 生成器,获得文本列表后手动处理列表: + +:: + + [text for text in soup.stripped_strings] + # [u'I linked to', u'example.com'] + +指定文档解析器 +============== + +如果仅是想要解析HTML文档,只要用文档创建 ``BeautifulSoup`` 对象就可以了.Beautiful Soup会自动选择一个解析器来解析文档.但是还可以通过参数指定使用那种解析器来解析当前文档. + +``BeautifulSoup`` 第一个参数应该是要被解析的文档字符串或是文件句柄,第二个参数用来标识怎样解析文档.如果第二个参数为空,那么Beautiful Soup根据当前系统安装的库自动选择解析器,解析器的优先数序: lxml, html5lib, Python标准库.在下面两种条件下解析器优先顺序会变化: + + * 要解析的文档是什么类型: 目前支持, “html”, “xml”, 和 “html5” + * 指定使用哪种解析器: 目前支持, “lxml”, “html5lib”, 和 “html.parser” + +`安装解析器`_ 章节介绍了可以使用哪种解析器,以及如何安装. + +如果指定的解析器没有安装,Beautiful Soup会自动选择其它方案.目前只有 lxml 解析器支持XML文档的解析,在没有安装lxml库的情况下,创建 ``beautifulsoup`` 对象时无论是否指定使用lxml,都无法得到解析后的对象 + +解析器之间的区别 +----------------- + +Beautiful Soup为不同的解析器提供了相同的接口,但解析器本身时有区别的.同一篇文档被不同的解析器解析后可能会生成不同结构的树型文档.区别最大的是HTML解析器和XML解析器,看下面片段被解析成HTML结构: + +:: + + BeautifulSoup("") + # + +因为空标签不符合HTML标准,所以解析器把它解析成 + +同样的文档使用XML解析如下(解析XML需要安装lxml库).注意,空标签依然被保留,并且文档前添加了XML头,而不是被包含在标签内: + +:: + + BeautifulSoup("", "xml") + # + # + +HTML解析器之间也有区别,如果被解析的HTML文档是标准格式,那么解析器之间没有任何差别,只是解析速度不同,结果都会返回正确的文档树. + +但是如果被解析文档不是标准格式,那么不同的解析器返回结果可能不同.下面例子中,使用lxml解析错误格式的文档,结果

标签被直接忽略掉了: + +:: + + BeautifulSoup("

", "lxml") + #
+ +使用html5lib库解析相同文档会得到不同的结果: + +:: + + BeautifulSoup("

", "html5lib") + #

+ +html5lib库没有忽略掉

标签,而是自动补全了标签,还给文档树添加了标签. + +使用pyhton内置库解析结果如下: + +:: + + BeautifulSoup("

", "html.parser") + #
+ +与lxml [7]_ 库类似的,Python内置库忽略掉了

标签,与html5lib库不同的是标准库没有尝试创建符合标准的文档格式或将文档片段包含在标签内,与lxml不同的是标准库甚至连标签都没有尝试去添加. + +因为文档片段“

”是错误格式,所以以上解析方式都能算作"正确",html5lib库使用的是HTML5的部分标准,所以最接近"正确".不过所有解析器的结构都能够被认为是"正常"的. + +不同的解析器可能影响代码执行结果,如果在分发给别人的代码中使用了 ``BeautifulSoup`` ,那么最好注明使用了哪种解析器,以减少不必要的麻烦. + +编码 +==== + +任何HTML或XML文档都有自己的编码方式,比如ASCII 或 UTF-8,但是使用Beautiful Soup解析后,文档都被转换成了Unicode: + +:: + + markup = "

Sacr\xc3\xa9 bleu!

" + soup = BeautifulSoup(markup) + soup.h1 + #

Sacré bleu!

+ soup.h1.string + # u'Sacr\xe9 bleu!' + +这不是魔术(但很神奇),Beautiful Soup用了 `编码自动检测`_ 子库来识别当前文档编码并转换成Unicode编码. ``BeautifulSoup`` 对象的 ``.original_encoding`` 属性记录了自动识别编码的结果: + +:: + + soup.original_encoding + 'utf-8' + +`编码自动检测`_ 功能大部分时候都能猜对编码格式,但有时候也会出错.有时候即使猜测正确,也是在逐个字节的遍历整个文档后才猜对的,这样很慢.如果预先知道文档编码,可以设置编码参数来减少自动检查编码出错的概率并且提高文档解析速度.在创建 ``BeautifulSoup`` 对象的时候设置 ``from_encoding`` 参数. + +下面一段文档用了ISO-8859-8编码方式,这段文档太短,结果Beautiful Soup以为文档是用ISO-8859-7编码: + +:: + + markup = b"

\xed\xe5\xec\xf9

" + soup = BeautifulSoup(markup) + soup.h1 +

νεμω

+ soup.original_encoding + 'ISO-8859-7' + +通过传入 ``from_encoding`` 参数来指定编码方式: + +:: + + soup = BeautifulSoup(markup, from_encoding="iso-8859-8") + soup.h1 +

םולש

+ soup.original_encoding + 'iso8859-8' + +如果仅知道文档采用了Unicode编码, 但不知道具体编码. 可以先自己猜测, 猜测错误(依旧是乱码)时, +可以把错误编码作为 ``exclude_encodings`` 参数, 这样文档就不会尝试使用这种编码了解码了. +译者备注: 在没有指定编码的情况下, BS会自己猜测编码, 把不正确的编码排除掉, BS就更容易猜到正确编码. + +:: + + soup = BeautifulSoup(markup, exclude_encodings=["ISO-8859-7"]) + soup.h1 +

םולש

+ soup.original_encoding + 'WINDOWS-1255' + +猜测结果是 Windows-1255 编码, 猜测结果可能不够准确, 但是 Windows-1255 编码是 ISO-8859-8 的扩展集, +所以猜测结果已经十分接近了, 并且不影响使用. (``exclude_encodings`` 参数是 4.4.0版本的新功能) + +少数情况下(通常是UTF-8编码的文档中包含了其它编码格式的文件),想获得正确的Unicode编码就不得不将文档中少数特殊编码字符替换成特殊Unicode编码,“REPLACEMENT CHARACTER” (U+FFFD, �) [9]_ . 如果Beautifu Soup猜测文档编码时作了特殊字符的替换,那么Beautiful Soup会把 ``UnicodeDammit`` 或 ``BeautifulSoup`` 对象的 ``.contains_replacement_characters`` 属性标记为 ``True`` .这样就可以知道当前文档进行Unicode编码后丢失了一部分特殊内容字符.如果文档中包含�而 ``.contains_replacement_characters`` 属性是 ``False`` ,则表示�就是文档中原来的字符,不是转码失败. + +输出编码 +-------- + +通过Beautiful Soup输出文档时,不管输入文档是什么编码方式,输出编码均为UTF-8编码,下面例子输入文档是Latin-1编码: + +:: + + markup = b''' + + + + + +

Sacr\xe9 bleu!

+ + + ''' + + soup = BeautifulSoup(markup) + print(soup.prettify()) + # + # + # + # + # + #

+ # Sacré bleu! + #

+ # + # + +注意,输出文档中的标签的编码设置已经修改成了与输出编码一致的UTF-8. + +如果不想用UTF-8编码输出,可以将编码方式传入 ``prettify()`` 方法: + +:: + + print(soup.prettify("latin-1")) + # + # + # + # ... + +还可以调用 ``BeautifulSoup`` 对象或任意节点的 ``encode()`` 方法,就像Python的字符串调用 ``encode()`` 方法一样: + +:: + + soup.p.encode("latin-1") + # '

Sacr\xe9 bleu!

' + + soup.p.encode("utf-8") + # '

Sacr\xc3\xa9 bleu!

' + +如果文档中包含当前编码不支持的字符,那么这些字符将被转换成一系列XML特殊字符引用,下面例子中包含了Unicode编码字符SNOWMAN: + +:: + + markup = u"\N{SNOWMAN}" + snowman_soup = BeautifulSoup(markup) + tag = snowman_soup.b + +SNOWMAN字符在UTF-8编码中可以正常显示(看上去像是☃),但有些编码不支持SNOWMAN字符,比如ISO-Latin-1或ASCII,那么在这些编码中SNOWMAN字符会被转换成“☃”: + +:: + + print(tag.encode("utf-8")) + # + + print tag.encode("latin-1") + # + + print tag.encode("ascii") + # + +Unicode, Dammit! (乱码, 靠!) +----------------------------- + +译者备注: UnicodeDammit 是BS内置库, 主要用来猜测文档编码. + +`编码自动检测`_ 功能可以在Beautiful Soup以外使用,检测某段未知编码时,可以使用这个方法: + +:: + + from bs4 import UnicodeDammit + dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!") + print(dammit.unicode_markup) + # Sacré bleu! + dammit.original_encoding + # 'utf-8' + +如果Python中安装了 ``chardet`` 或 ``cchardet`` 那么编码检测功能的准确率将大大提高. +输入的字符越多,检测结果越精确,如果事先猜测到一些可能编码, +那么可以将猜测的编码作为参数,这样将优先检测这些编码: + +:: + + + dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"]) + print(dammit.unicode_markup) + # Sacré bleu! + dammit.original_encoding + # 'latin-1' + +`编码自动检测`_ 功能中有2项功能是Beautiful Soup库中用不到的 + +智能引号 +........... + +使用Unicode时,Beautiful Soup还会智能的把引号 [10]_ 转换成HTML或XML中的特殊字符: + +:: + + markup = b"

I just \x93love\x94 Microsoft Word\x92s smart quotes

" + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup + # u'

I just “love” Microsoft Word’s smart quotes

' + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup + # u'

I just “love” Microsoft Word’s smart quotes

' + +也可以把引号转换为ASCII码: + +:: + + UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup + # u'

I just "love" Microsoft Word\'s smart quotes

' + +很有用的功能,但是Beautiful Soup没有使用这种方式.默认情况下,Beautiful Soup把引号转换成Unicode: + +:: + + UnicodeDammit(markup, ["windows-1252"]).unicode_markup + # u'

I just \u201clove\u201d Microsoft Word\u2019s smart quotes

' + +矛盾的编码 +........... + +有时文档的大部分都是用UTF-8,但同时还包含了Windows-1252编码的字符,就像微软的智能引号 [10]_ 一样. +一些包含多个信息的来源网站容易出现这种情况. ``UnicodeDammit.detwingle()`` +方法可以把这类文档转换成纯UTF-8编码格式,看个简单的例子: + +:: + + snowmen = (u"\N{SNOWMAN}" * 3) + quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}") + doc = snowmen.encode("utf8") + quote.encode("windows_1252") + +这段文档很杂乱,snowmen是UTF-8编码,引号是Windows-1252编码,直接输出时不能同时显示snowmen和引号,因为它们编码不同: + +:: + + print(doc) + # ☃☃☃�I like snowmen!� + + print(doc.decode("windows-1252")) + # ☃☃☃“I like snowmen!” + +如果对这段文档用UTF-8解码就会得到 ``UnicodeDecodeError`` 异常,如果用Windows-1252解码就回得到一堆乱码. +幸好, ``UnicodeDammit.detwingle()`` 方法会把这段字符串转换成UTF-8编码,允许我们同时显示出文档中的snowmen和引号: + +:: + + new_doc = UnicodeDammit.detwingle(doc) + print(new_doc.decode("utf8")) + # ☃☃☃“I like snowmen!” + +``UnicodeDammit.detwingle()`` 方法只能解码包含在UTF-8编码中的Windows-1252编码内容,但这解决了最常见的一类问题. + +在创建 ``BeautifulSoup`` 或 ``UnicodeDammit`` 对象前一定要先对文档调用 ``UnicodeDammit.detwingle()`` 确保文档的编码方式正确.如果尝试去解析一段包含Windows-1252编码的UTF-8文档,就会得到一堆乱码,比如: ☃☃☃“I like snowmen!”. + +``UnicodeDammit.detwingle()`` 方法在Beautiful Soup 4.1.0版本中新增 + +比较对象是否相同 +================= + +两个 ``NavigableString`` 或 ``Tag`` 对象具有相同的HTML或XML结构时, +Beautiful Soup就判断这两个对象相同. 这个例子中, 2个 标签在 BS 中是相同的, +尽管他们在文档树的不同位置, 但是具有相同的表象: "pizza" + +:: + + markup = "

I want pizza and more pizza!

" + soup = BeautifulSoup(markup, 'html.parser') + first_b, second_b = soup.find_all('b') + print first_b == second_b + # True + + print first_b.previous_element == second_b.previous_element + # False + +如果想判断两个对象是否严格的指向同一个对象可以通过 ``is`` 来判断 + +:: + + print first_b is second_b + # False + +复制Beautiful Soup对象 +====================== + +``copy.copy()`` 方法可以复制任意 ``Tag`` 或 ``NavigableString`` 对象 + +:: + + import copy + p_copy = copy.copy(soup.p) + print p_copy + #

I want pizza and more pizza!

+ +复制后的对象跟与对象是相等的, 但指向不同的内存地址 + +:: + + print soup.p == p_copy + # True + + print soup.p is p_copy + # False + +源对象和复制对象的区别是源对象在文档树中, 而复制后的对象是独立的还没有添加到文档树中. +复制后对象的效果跟调用了 ``extract()`` 方法相同. + +:: + + print p_copy.parent + # None + +这是因为相等的对象不能同时插入相同的位置 + + +解析部分文档 +============ + +如果仅仅因为想要查找文档中的
标签而将整片文档进行解析,实在是浪费内存和时间.最快的方法是从一开始就把标签以外的东西都忽略掉. ``SoupStrainer`` 类可以定义文档的某段内容,这样搜索文档时就不必先解析整篇文档,只会解析在 ``SoupStrainer`` 中定义过的文档. 创建一个 ``SoupStrainer`` 对象并作为 ``parse_only`` 参数给 ``BeautifulSoup`` 的构造方法即可. + +SoupStrainer +------------- + +``SoupStrainer`` 类接受与典型搜索方法相同的参数:`name`_ , `attrs`_ , `recursive`_ , `string`_ , `**kwargs`_ 。下面举例说明三种 ``SoupStrainer`` 对象: + +:: + + from bs4 import SoupStrainer + + only_a_tags = SoupStrainer("a") + + only_tags_with_id_link2 = SoupStrainer(id="link2") + + def is_short_string(string): + return len(string) < 10 + + only_short_strings = SoupStrainer(string=is_short_string) + +再拿“爱丽丝”文档来举例,来看看使用三种 ``SoupStrainer`` 对象做参数会有什么不同: + +:: + + html_doc = """ + The Dormouse's story + +

The Dormouse's story

+ +

Once upon a time there were three little sisters; and their names were + Elsie, + Lacie and + Tillie; + and they lived at the bottom of a well.

+ +

...

+ """ + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify()) + # + # Elsie + # + # + # Lacie + # + # + # Tillie + # + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify()) + # + # Lacie + # + + print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify()) + # Elsie + # , + # Lacie + # and + # Tillie + # ... + # + +还可以将 ``SoupStrainer`` 作为参数传入 `搜索文档树`_ 中提到的方法.这可能不是个常用用法,所以还是提一下: + +:: + + soup = BeautifulSoup(html_doc) + soup.find_all(only_short_strings) + # [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie', + # u'\n\n', u'...', u'\n'] + +常见问题 +======== + +代码诊断 +---------- + +如果想知道Beautiful Soup到底怎样处理一份文档,可以将文档传入 ``diagnose()`` 方法(Beautiful Soup 4.2.0中新增),Beautiful Soup会输出一份报告,说明不同的解析器会怎样处理这段文档,并标出当前的解析过程会使用哪种解析器: + +:: + + from bs4.diagnose import diagnose + data = open("bad.html").read() + diagnose(data) + + # Diagnostic running on Beautiful Soup 4.2.0 + # Python version 2.7.3 (default, Aug 1 2012, 05:16:07) + # I noticed that html5lib is not installed. Installing it may help. + # Found lxml version 2.3.2.0 + # + # Trying to parse your data with html.parser + # Here's what html.parser did with the document: + # ... + +``diagnose()`` 方法的输出结果可能帮助你找到问题的原因,如果不行,还可以把结果复制出来以便寻求他人的帮助 + +文档解析错误 +------------- + +文档解析错误有两种.一种是崩溃,Beautiful Soup尝试解析一段文档结果却抛除了异常,通常是 ``HTMLParser.HTMLParseError`` .还有一种异常情况,是Beautiful Soup解析后的文档树看起来与原来的内容相差很多. + +这些错误几乎都不是Beautiful Soup的原因,这不会是因为Beautiful Soup的代码写的太优秀,而是因为Beautiful Soup没有包含任何文档解析代码.异常产生自被依赖的解析器,如果解析器不能很好的解析出当前的文档,那么最好的办法是换一个解析器.更多细节查看 `安装解析器`_ 章节. + +最常见的解析错误是 ``HTMLParser.HTMLParseError: malformed start tag`` 和 ``HTMLParser.HTMLParseError: bad end tag`` .这都是由Python内置的解析器引起的,解决方法是 `安装lxml或html5lib`_ + +最常见的异常现象是当前文档找不到指定的Tag,而这个Tag光是用眼睛就足够发现的了. ``find_all()`` 方法返回 [] ,而 ``find()`` 方法返回 None .这是Python内置解析器的又一个问题: 解析器会跳过那些它不知道的tag.解决方法还是 `安装lxml或html5lib`_ + +版本错误 +---------- + +* ``SyntaxError: Invalid syntax`` (异常位置在代码行: ``ROOT_TAG_NAME = u'[document]'`` ),因为Python2语法的代码(没有经过迁移)直接在Python3中运行 + +* ``ImportError: No module named HTMLParser`` 因为在Python3中执行Python2版本的Beautiful Soup + +* ``ImportError: No module named html.parser`` 因为在Python2中执行Python3版本的Beautiful Soup + +* ``ImportError: No module named BeautifulSoup`` 因为在没有安装BeautifulSoup3库的Python环境下执行代码,或忘记了BeautifulSoup4的代码需要从 ``bs4`` 包中引入 + +* ``ImportError: No module named bs4`` 因为当前Python环境下还没有安装BeautifulSoup4 + +解析成XML +---------- + +默认情况下,Beautiful Soup会将当前文档作为HTML格式解析,如果要解析XML文档,要在 ``BeautifulSoup`` 构造方法中加入第二个参数 "xml": + +:: + + soup = BeautifulSoup(markup, "xml") + +当然,还需要 `安装lxml`_ + +解析器的错误 +------------ + +* 如果同样的代码在不同环境下结果不同,可能是因为两个环境下使用不同的解析器造成的.例如这个环境中安装了lxml,而另一个环境中只有html5lib, `解析器之间的区别`_ 中说明了原因.修复方法是在 ``BeautifulSoup`` 的构造方法中中指定解析器 + +* 因为HTML标签是 `大小写敏感 `_ 的,所以3种解析器再出来文档时都将tag和属性转换成小写.例如文档中的 会被转换为 .如果想要保留tag的大写的话,那么应该将文档 `解析成XML`_ . + +杂项错误 +-------- + +* ``UnicodeEncodeError: 'charmap' codec can't encode character u'\xfoo' in position bar`` (或其它类型的 ``UnicodeEncodeError`` )的错误,主要是两方面的错误(都不是Beautiful Soup的原因),第一种是正在使用的终端(console)无法显示部分Unicode,参考 `Python wiki `_ ,第二种是向文件写入时,被写入文件不支持部分Unicode,这时只要用 ``u.encode("utf8")`` 方法将编码转换为UTF-8. + +* ``KeyError: [attr]`` 因为调用 ``tag['attr']`` 方法而引起,因为这个tag没有定义该属性.出错最多的是 ``KeyError: 'href'`` 和 ``KeyError: 'class'`` .如果不确定某个属性是否存在时,用 ``tag.get('attr')`` 方法去获取它,跟获取Python字典的key一样 + +* ``AttributeError: 'ResultSet' object has no attribute 'foo'`` 错误通常是因为把 ``find_all()`` 的返回结果当作一个tag或文本节点使用,实际上返回结果是一个列表或 ``ResultSet`` 对象的字符串,需要对结果进行循环才能得到每个节点的 ``.foo`` 属性.或者使用 ``find()`` 方法仅获取到一个节点 + +* ``AttributeError: 'NoneType' object has no attribute 'foo'`` 这个错误通常是在调用了 ``find()`` 方法后直节点取某个属性 .foo 但是 ``find()`` 方法并没有找到任何结果,所以它的返回值是 ``None`` .需要找出为什么 ``find()`` 的返回值是 ``None`` . + +如何提高效率 +------------ + +Beautiful Soup对文档的解析速度不会比它所依赖的解析器更快,如果对计算时间要求很高或者计算机的时间比程序员的时间更值钱,那么就应该直接使用 `lxml `_ . + +换句话说,还有提高Beautiful Soup效率的办法,使用lxml作为解析器.Beautiful Soup用lxml做解析器比用html5lib或Python内置解析器速度快很多. + +安装 `cchardet `_ 后文档的解码的编码检测会速度更快 + +`解析部分文档`_ 不会节省多少解析时间,但是会节省很多内存,并且搜索时也会变得更快. + +Beautiful Soup 3 +================= + +Beautiful Soup 3是上一个发布版本,目前已经停止维护.Beautiful Soup 3库目前已经被几个主要的linux平台添加到源里: + +``$ apt-get install Python-beautifulsoup`` + +在PyPi中分发的包名字是 ``BeautifulSoup`` : + +``$ easy_install BeautifulSoup`` + +``$ pip install BeautifulSoup`` + +或通过 `Beautiful Soup 3.2.0源码包 `_ 安装 + +Beautiful Soup 3的在线文档查看 `这里 `_ . + +迁移到BS4 +---------- + +只要一个小变动就能让大部分的Beautiful Soup 3代码使用Beautiful Soup 4的库和方法----修改 ``BeautifulSoup`` 对象的引入方式: + +:: + + from BeautifulSoup import BeautifulSoup + +修改为: + +:: + + from bs4 import BeautifulSoup + +* 如果代码抛出 ``ImportError`` 异常“No module named BeautifulSoup”,原因可能是尝试执行Beautiful Soup 3,但环境中只安装了Beautiful Soup 4库 + +* 如果代码跑出 ``ImportError`` 异常“No module named bs4”,原因可能是尝试运行Beautiful Soup 4的代码,但环境中只安装了Beautiful Soup 3. + +虽然BS4兼容绝大部分BS3的功能,但BS3中的大部分方法已经不推荐使用了,就方法按照 `PEP8标准 `_ 重新定义了方法名.很多方法都重新定义了方法名,但只有少数几个方法没有向下兼容. + +上述内容就是BS3迁移到BS4的注意事项 + +需要的解析器 +............ + +Beautiful Soup 3曾使用Python的 ``SGMLParser`` 解析器,这个模块在Python3中已经被移除了.Beautiful Soup 4默认使用系统的 ``html.parser`` ,也可以使用lxml或html5lib扩展库代替.查看 `安装解析器`_ 章节 + +因为解析器 ``html.parser`` 与 ``SGMLParser`` 不同. BS4 和 BS3 处理相同的文档会产生不同的对象结构. 使用lxml或html5lib解析文档的时候, 如果添加了 ``html.parser`` 参数, 解析的对象又回发生变化. 如果发生了这种情况, 只能修改对应的处文档结果处理代码了. + +方法名的变化 +............ + +* ``renderContents`` -> ``encode_contents`` + +* ``replaceWith`` -> ``replace_with`` + +* ``replaceWithChildren`` -> ``unwrap`` + +* ``findAll`` -> ``find_all`` + +* ``findAllNext`` -> ``find_all_next`` + +* ``findAllPrevious`` -> ``find_all_previous`` + +* ``findNext`` -> ``find_next`` + +* ``findNextSibling`` -> ``find_next_sibling`` + +* ``findNextSiblings`` -> ``find_next_siblings`` + +* ``findParent`` -> ``find_parent`` + +* ``findParents`` -> ``find_parents`` + +* ``findPrevious`` -> ``find_previous`` + +* ``findPreviousSibling`` -> ``find_previous_sibling`` + +* ``findPreviousSiblings`` -> ``find_previous_siblings`` + +* ``nextSibling`` -> ``next_sibling`` + +* ``previousSibling`` -> ``previous_sibling`` + +Beautiful Soup构造方法的参数部分也有名字变化: + +* ``BeautifulSoup(parseOnlyThese=...)`` -> ``BeautifulSoup(parse_only=...)`` + +* ``BeautifulSoup(fromEncoding=...)`` -> ``BeautifulSoup(from_encoding=...)`` + +为了适配Python3,修改了一个方法名: + +* ``Tag.has_key()`` -> ``Tag.has_attr()`` + +修改了一个属性名,让它看起来更专业点: + +* ``Tag.isSelfClosing`` -> ``Tag.is_empty_element`` + +修改了下面3个属性的名字,以免雨Python保留字冲突.这些变动不是向下兼容的,如果在BS3中使用了这些属性,那么在BS4中这些代码无法执行. + +* UnicodeDammit.Unicode -> UnicodeDammit.Unicode_markup`` + +* ``Tag.next`` -> ``Tag.next_element`` + +* ``Tag.previous`` -> ``Tag.previous_element`` + +生成器 +....... + +将下列生成器按照PEP8标准重新命名,并转换成对象的属性: + +* ``childGenerator()`` -> ``children`` + +* ``nextGenerator()`` -> ``next_elements`` + +* ``nextSiblingGenerator()`` -> ``next_siblings`` + +* ``previousGenerator()`` -> ``previous_elements`` + +* ``previousSiblingGenerator()`` -> ``previous_siblings`` + +* ``recursiveChildGenerator()`` -> ``descendants`` + +* ``parentGenerator()`` -> ``parents`` + +所以迁移到BS4版本时要替换这些代码: + +:: + + for parent in tag.parentGenerator(): + ... + +替换为: + +:: + + for parent in tag.parents: + ... + +(两种调用方法现在都能使用) + +BS3中有的生成器循环结束后会返回 ``None`` 然后结束.这是个bug.新版生成器不再返回 ``None`` . + +BS4中增加了2个新的生成器, `.strings 和 stripped_strings`_ . ``.strings`` 生成器返回NavigableString对象, ``.stripped_strings`` 方法返回去除前后空白的Python的string对象. + +XML +.... + +BS4中移除了解析XML的 ``BeautifulStoneSoup`` 类.如果要解析一段XML文档,使用 ``BeautifulSoup`` 构造方法并在第二个参数设置为“xml”.同时 ``BeautifulSoup`` 构造方法也不再识别 ``isHTML`` 参数. + +Beautiful Soup处理XML空标签的方法升级了.旧版本中解析XML时必须指明哪个标签是空标签. 构造方法的 ``selfClosingTags`` 参数已经不再使用.新版Beautiful Soup将所有空标签解析为空元素,如果向空元素中添加子节点,那么这个元素就不再是空元素了. + +实体 +..... + +HTML或XML实体都会被解析成Unicode字符,Beautiful Soup 3版本中有很多处理实体的方法,在新版中都被移除了. ``BeautifulSoup`` 构造方法也不再接受 ``smartQuotesTo`` 或 ``convertEntities`` 参数. `编码自动检测`_ 方法依然有 ``smart_quotes_to`` 参数,但是默认会将引号转换成Unicode.内容配置项 ``HTML_ENTITIES`` , ``XML_ENTITIES`` 和 ``XHTML_ENTITIES`` 在新版中被移除.因为它们代表的特性已经不再被支持. + +如果在输出文档时想把Unicode字符转换成HTML实体,而不是输出成UTF-8编码,那就需要用到 `输出格式`_ 的方法. + +迁移杂项 +......... + +`Tag.string`_ 属性现在是一个递归操作.如果A标签只包含了一个B标签,那么A标签的.string属性值与B标签的.string属性值相同. + +`多值属性`_ 比如 ``class`` 属性包含一个他们的值的列表,而不是一个字符串.这可能会影响到如何按照CSS类名哦搜索tag. + +如果使用 ``find*`` 方法时同时传入了 `string 参数`_ 和 `name 参数`_ .Beautiful Soup会搜索指定name的tag,并且这个tag的 `Tag.string`_ 属性包含text参数的内容.结果中不会包含字符串本身.旧版本中Beautiful Soup会忽略掉tag参数,只搜索text参数. + +``BeautifulSoup`` 构造方法不再支持 markupMassage 参数.现在由解析器负责文档的解析正确性. + +很少被用到的几个解析器方法在新版中被移除,比如 ``ICantBelieveItsBeautifulSoup`` 和 ``BeautifulSOAP`` .现在由解析器完全负责如何解释模糊不清的文档标记. + +``prettify()`` 方法在新版中返回Unicode字符串,不再返回字节流. + +附录 +===== + +.. _`BeautifulSoup3 文档`: http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html +.. _name: `name 参数`_ +.. _attrs: `按CSS搜索`_ +.. _recursive: `recursive 参数`_ +.. _string: `string 参数`_ +.. _**kwargs: `keyword 参数`_ +.. _.next_siblings: `.next_siblings 和 .previous_siblings`_ +.. _.previous_siblings: `.next_siblings 和 .previous_siblings`_ +.. _.next_elements: `.next_elements 和 .previous_elements`_ +.. _.previous_elements: `.next_elements 和 .previous_elements`_ +.. _.stripped_strings: `.strings 和 stripped_strings`_ +.. _安装lxml: `安装解析器`_ +.. _安装lxml或html5lib: `安装解析器`_ +.. _编码自动检测: `Unicode, Dammit! (乱码, 靠!)`_ +.. _Tag.string: `.string`_ + + +.. [1] BeautifulSoup的google讨论组不是很活跃,可能是因为库已经比较完善了吧,但是作者还是会很热心的尽量帮你解决问题的. +.. [2] 文档被解析成树形结构,所以下一步解析过程应该是当前节点的子节点 +.. [3] 过滤器只能作为搜索文档的参数,或者说应该叫参数类型更为贴切,原文中用了 ``filter`` 因此翻译为过滤器 +.. [4] 元素参数,HTML文档中的一个tag节点,不能是文本节点 +.. [5] 采用先序遍历方式 +.. [6] CSS选择器是一种单独的文档搜索语法, 参考 http://www.w3school.com.cn/css/css_selector_type.asp +.. [7] 原文写的是 html5lib, 译者觉得这是原文档的一个笔误 +.. [8] wrap含有包装,打包的意思,但是这里的包装不是在外部包装而是将当前tag的内部内容包装在一个tag里.包装原来内容的新tag依然在执行 `wrap()`_ 方法的tag内 +.. [9] 文档中特殊编码字符被替换成特殊字符(通常是�)的过程是Beautful Soup自动实现的,如果想要多种编码格式的文档被完全转换正确,那么,只好,预先手动处理,统一编码格式 +.. [10] 智能引号,常出现在microsoft的word软件中,即在某一段落中按引号出现的顺序每个引号都被自动转换为左引号,或右引号. + +原文: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ + +翻译: Deron Wang + +查看 `BeautifulSoup3 文档`_ diff --git a/doc.zh/source/index.zh.html b/doc.zh/source/index.zh.html deleted file mode 100644 index 71ea360..0000000 --- a/doc.zh/source/index.zh.html +++ /dev/null @@ -1,2398 +0,0 @@ - - - - - - - - Beautiful Soup 4.2.0 文档 — Beautiful Soup 4.2.0 documentation - - - - - - - - - - - - - -
-
-
-
- -
-

Beautiful Soup 4.2.0 文档

-_static/cover.jpg -

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.

-

这篇文档介绍了BeautifulSoup4中所有主要特性,并切有小例子.让我来向你展示它适合做什么,如何工作,怎样使用,如何达到你想要的效果,和处理异常情况.

-

文档中出现的例子在Python2.7和Python3.2中的执行结果相同

-

你可能在寻找 Beautiful Soup3 的文档,Beautiful Soup 3 目前已经停止开发,我们推荐在现在的项目中使用Beautiful Soup 4, 移植到BS4

-
-

寻求帮助

-

如果你有关于BeautifulSoup的问题,可以发送邮件到 讨论组 .如果你的问题包含了一段需要转换的HTML代码,那么确保你提的问题描述中附带这段HTML文档的 代码诊断 [1]

-
-
-
-

快速开始

-

下面的一段HTML代码将作为例子被多次用到.这是 爱丽丝梦游仙境的 的一段内容(以后内容中简称为 爱丽丝 的文档):

-
html_doc = """
-<html><head><title>The Dormouse's story</title></head>
-<body>
-<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>
-"""
-
-
-

使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:

-
from bs4 import BeautifulSoup
-soup = BeautifulSoup(html_doc)
-
-print(soup.prettify())
-# <html>
-#  <head>
-#   <title>
-#    The Dormouse's story
-#   </title>
-#  </head>
-#  <body>
-#   <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 class="sister" href="http://example.com/elsie" id="link1">
-#     Elsie
-#    </a>
-#    ,
-#    <a class="sister" href="http://example.com/lacie" id="link2">
-#     Lacie
-#    </a>
-#    and
-#    <a class="sister" href="http://example.com/tillie" id="link2">
-#     Tillie
-#    </a>
-#    ; and they lived at the bottom of a well.
-#   </p>
-#   <p class="story">
-#    ...
-#   </p>
-#  </body>
-# </html>
-
-
-

几个简单的浏览结构化数据的方法:

-
soup.title
-# <title>The Dormouse's story</title>
-
-soup.title.name
-# u'title'
-
-soup.title.string
-# u'The Dormouse's story'
-
-soup.title.parent.name
-# u'head'
-
-soup.p
-# <p class="title"><b>The Dormouse's story</b></p>
-
-soup.p['class']
-# u'title'
-
-soup.a
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-soup.find_all('a')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.find(id="link3")
-# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
-
-
-

从文档中找到所有<a>标签的链接:

-
for link in soup.find_all('a'):
-    print(link.get('href'))
-    # http://example.com/elsie
-    # http://example.com/lacie
-    # http://example.com/tillie
-
-
-

从文档中获取所有文字内容:

-
print(soup.get_text())
-# The Dormouse's story
-#
-# The Dormouse's story
-#
-# Once upon a time there were three little sisters; and their names were
-# Elsie,
-# Lacie and
-# Tillie;
-# and they lived at the bottom of a well.
-#
-# ...
-
-
-

这是你想要的吗?别着急,还有更好用的

-
-
-

安装 Beautiful Soup

-

如果你用的是新版的Debain或ubuntu,那么可以通过系统的软件包管理来安装:

-

$ apt-get install Python-bs4

-

Beautiful Soup 4 通过PyPi发布,所以如果你无法使用系统包管理安装,那么也可以通过 easy_installpip 来安装.包的名字是 beautifulsoup4 ,这个包兼容Python2和Python3.

-

$ easy_install beautifulsoup4

-

$ pip install beautifulsoup4

-

(在PyPi中还有一个名字是 BeautifulSoup 的包,但那可能不是你想要的,那是 Beautiful Soup3 的发布版本,因为很多项目还在使用BS3, 所以 BeautifulSoup 包依然有效.但是如果你在编写新项目,那么你应该安装的 beautifulsoup4 )

-

如果你没有安装 easy_installpip ,那你也可以 下载BS4的源码 ,然后通过setup.py来安装.

-

$ Python setup.py install

-

如果上述安装方法都行不通,Beautiful Soup的发布协议允许你将BS4的代码打包在你的项目中,这样无须安装即可使用.

-

作者在Python2.7和Python3.2的版本下开发Beautiful Soup, 理论上Beautiful Soup应该在所有当前的Python版本中正常工作

-
-

安装完成后的问题

-

Beautiful Soup发布时打包成Python2版本的代码,在Python3环境下安装时,会自动转换成Python3的代码,如果没有一个安装的过程,那么代码就不会被转换.

-

如果代码抛出了 ImportError 的异常: “No module named HTMLParser”, 这是因为你在Python3版本中执行Python2版本的代码.

-

如果代码抛出了 ImportError 的异常: “No module named html.parser”, 这是因为你在Python2版本中执行Python3版本的代码.

-

如果遇到上述2种情况,最好的解决方法是重新安装BeautifulSoup4.

-

如果在ROOT_TAG_NAME = u’[document]’代码处遇到 SyntaxError “Invalid syntax”错误,需要将把BS4的Python代码版本从Python2转换到Python3. 可以重新安装BS4:

-

$ Python3 setup.py install

-

或在bs4的目录中执行Python代码版本转换脚本

-

$ 2to3-3.2 -w bs4

-
-
-

安装解析器

-

Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:

-

$ apt-get install Python-lxml

-

$ easy_install lxml

-

$ pip install lxml

-

另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

-

$ apt-get install Python-html5lib

-

$ easy_install html5lib

-

$ pip install html5lib

-

下表列出了主要的解析器,以及它们的优缺点:

- ------ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
解析器使用方法优势劣势
Python标准库BeautifulSoup(markup, -"html.parser")
    -
  • Python的内置标准库
  • -
  • 执行速度适中
  • -
  • 文档容错能力强
  • -
-
    -
  • Python 2.7.3 or 3.2.2)前 -的版本中文档容错能力差
  • -
-
lxml HTML 解析器BeautifulSoup(markup, -"lxml")
    -
  • 速度快
  • -
  • 文档容错能力强
  • -
-
    -
  • 需要安装C语言库
  • -
-
lxml XML 解析器

BeautifulSoup(markup, -["lxml", "xml"])

-

BeautifulSoup(markup, -"xml")

-
    -
  • 速度快
  • -
  • 唯一支持XML的解析器
  • -
-
    -
  • 需要安装C语言库
  • -
-
html5libBeautifulSoup(markup, -"html5lib")
    -
  • 最好的容错性
  • -
  • 以浏览器的方式解析文档
  • -
  • 生成HTML5格式的文档
  • -
-
    -
  • 速度慢
  • -
  • 不依赖外部扩展
  • -
-
-

推荐使用lxml作为解析器,因为效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必须安装lxml或html5lib, 因为那些Python版本的标准库中内置的HTML解析方法不够稳定.

-

提示: 如果一段HTML或XML文档格式不正确的话,那么在不同的解析器中返回的结果可能是不一样的,查看 解析器之间的区别 了解更多细节

-
-
-
-

如何使用

-

将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄.

-
from bs4 import BeautifulSoup
-
-soup = BeautifulSoup(open("index.html"))
-
-soup = BeautifulSoup("<html>data</html>")
-
-
-

首先,文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码

-
BeautifulSoup("Sacr&eacute; bleu!")
-<html><head></head><body>Sacré bleu!</body></html>
-
-

然后,Beautiful Soup选择最合适的解析器来解析这段文档,如果手动指定解析器那么Beautiful Soup会选择指定的解析器来解析文档.(参考 解析成XML ).

-
-
-

对象的种类

-

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .

-
-

Tag

-

Tag 对象与XML或HTML原生文档中的tag相同:

-
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
-tag = soup.b
-type(tag)
-# <class 'bs4.element.Tag'>
-
-
-

Tag有很多方法和属性,在 遍历文档树搜索文档树 中有详细解释.现在介绍一下tag中最重要的属性: name和attributes

-
-

Name

-

每个tag都有自己的名字,通过 .name 来获取:

-
tag.name
-# u'b'
-
-
-

如果改变了tag的name,那将影响所有通过当前Beautiful Soup对象生成的HTML文档:

-
tag.name = "blockquote"
-tag
-# <blockquote class="boldest">Extremely bold</blockquote>
-
-
-
-
-

Attributes

-

一个tag可能有很多个属性. tag <b class="boldest"> 有一个 “class” 的属性,值为 “boldest” . tag的属性的操作方法与字典相同:

-
tag['class']
-# u'boldest'
-
-
-

也可以直接”点”取属性, 比如: .attrs :

-
tag.attrs
-# {u'class': u'boldest'}
-
-
-

tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样

-
tag['class'] = 'verybold'
-tag['id'] = 1
-tag
-# <blockquote class="verybold" id="1">Extremely bold</blockquote>
-
-del tag['class']
-del tag['id']
-tag
-# <blockquote>Extremely bold</blockquote>
-
-tag['class']
-# KeyError: 'class'
-print(tag.get('class'))
-# None
-
-
-
-

多值属性

-

HTML 4定义了一系列可以包含多个值的属性.在HTML5中移除了一些,却增加更多.最常见的多值的属性是 class (一个tag可以有多个CSS的class). 还有一些属性 rel , rev , accept-charset , headers , accesskey . 在Beautiful Soup中多值属性的返回类型是list:

-
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
-css_soup.p['class']
-# ["body", "strikeout"]
-
-css_soup = BeautifulSoup('<p class="body"></p>')
-css_soup.p['class']
-# ["body"]
-
-
-

如果某个属性看起来好像有多个值,但在任何版本的HTML定义中都没有被定义为多值属性,那么Beautiful Soup会将这个属性作为字符串返回

-
id_soup = BeautifulSoup('<p id="my id"></p>')
-id_soup.p['id']
-# 'my id'
-
-
-

将tag转换成字符串时,多值属性会合并为一个值

-
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>')
-rel_soup.a['rel']
-# ['index']
-rel_soup.a['rel'] = ['index', 'contents']
-print(rel_soup.p)
-# <p>Back to the <a rel="index contents">homepage</a></p>
-
-
-

如果转换的文档是XML格式,那么tag中不包含多值属性

-
xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml')
-xml_soup.p['class']
-# u'body strikeout'
-
-
-
-
-
-
-

可以遍历的字符串

-

字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串:

-
tag.string
-# u'Extremely bold'
-type(tag.string)
-# <class 'bs4.element.NavigableString'>
-
-
-

一个 NavigableString 字符串与Python中的Unicode字符串相同,并且还支持包含在 遍历文档树搜索文档树 中的一些特性. 通过 unicode() 方法可以直接将 NavigableString 对象转换成Unicode字符串:

-
unicode_string = unicode(tag.string)
-unicode_string
-# u'Extremely bold'
-type(unicode_string)
-# <type 'unicode'>
-
-
-

tag中包含的字符串不能编辑,但是可以被替换成其它的字符串,用 replace_with() 方法:

-
tag.string.replace_with("No longer bold")
-tag
-# <blockquote>No longer bold</blockquote>
-
-
-

NavigableString 对象支持 遍历文档树搜索文档树 中定义的大部分属性, 并非全部.尤其是,一个字符串不能包含其它内容(tag能够包含字符串或是其它tag),字符串不支持 .contents.string 属性或 find() 方法.

-

如果想在Beautiful Soup之外使用 NavigableString 对象,需要调用 unicode() 方法,将该对象转换成普通的Unicode字符串,否则就算Beautiful Soup已方法已经执行结束,该对象的输出也会带有对象的引用地址.这样会浪费内存.

-
-
-

BeautifulSoup

-

BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,它支持 遍历文档树搜索文档树 中描述的大部分的方法.

-

因为 BeautifulSoup 对象并不是真正的HTML或XML的tag,所以它没有name和attribute属性.但有时查看它的 .name 属性是很方便的,所以 BeautifulSoup 对象包含了一个值为 “[document]” 的特殊属性 .name

-
soup.name
-# u'[document]'
-
-
-
-
-

注释及特殊字符串

-

Tag , 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'>
-
-
-

Comment 对象是一个特殊类型的 NavigableString 对象:

-
comment
-# u'Hey, buddy. Want to buy a used parser'
-
-
-

但是当它出现在HTML文档中时, Comment 对象会使用特殊的格式输出:

-
print(soup.b.prettify())
-# <b>
-#  <!--Hey, buddy. Want to buy a used parser?-->
-# </b>
-
-
-

Beautiful Soup中定义的其它类型都可能会出现在XML的文档中: CData , ProcessingInstruction , Declaration , Doctype .与 Comment 对象类似,这些类都是 NavigableString 的子类,只是添加了一些额外的方法的字符串独享.下面是用CDATA来替代注释的例子:

-
from bs4 import CData
-cdata = CData("A CDATA block")
-comment.replace_with(cdata)
-
-print(soup.b.prettify())
-# <b>
-#  <![CDATA[A CDATA block]]>
-# </b>
-
-
-
-
-
-

遍历文档树

-

还拿”爱丽丝梦游仙境”的文档来做例子:

-
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)
-
-
-

通过这段例子来演示怎样从文档的一段内容找到另一段内容

-
-

子节点

-

一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性.

-

注意: Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点

-
-

tag的名字

-

操作文档树最简单的方法就是告诉它你想获取的tag的name.如果想获取 <head> 标签,只要用 soup.head :

-
soup.head
-# <head><title>The Dormouse's story</title></head>
-
-soup.title
-# <title>The Dormouse's story</title>
-
-
-

这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取<body>标签中的第一个<b>标签:

-
soup.body.b
-# <b>The Dormouse's story</b>
-
-
-

通过点取属性的方式只能获得当前名字的第一个tag:

-
soup.a
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-
-

如果想要得到所有的<a>标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 Searching the tree 中描述的方法,比如: find_all()

-
soup.find_all('a')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-
-
-

.contents 和 .children

-

tag的 .contents 属性可以将tag的子节点以列表的方式输出:

-
head_tag = soup.head
-head_tag
-# <head><title>The Dormouse's story</title></head>
-
-head_tag.contents
-[<title>The Dormouse's story</title>]
-
-title_tag = head_tag.contents[0]
-title_tag
-# <title>The Dormouse's story</title>
-title_tag.contents
-# [u'The Dormouse's story']
-
-

BeautifulSoup 对象本身一定会包含子节点,也就是说<html>标签也是 BeautifulSoup 对象的子节点:

-
len(soup.contents)
-# 1
-soup.contents[0].name
-# u'html'
-
-
-

字符串没有 .contents 属性,因为字符串没有子节点:

-
text = title_tag.contents[0]
-text.contents
-# AttributeError: 'NavigableString' object has no attribute 'contents'
-
-
-

通过tag的 .children 生成器,可以对tag的子节点进行循环:

-
for child in title_tag.children:
-    print(child)
-    # The Dormouse's story
-
-
-
-
-

.descendants

-

.contents.children 属性仅包含tag的直接子节点.例如,<head>标签只有一个直接子节点<title>

-
head_tag.contents
-# [<title>The Dormouse's story</title>]
-
-
-

但是<title>标签也包含一个子节点:字符串 “The Dormouse’s story”,这种情况下字符串 “The Dormouse’s story”也属于<head>标签的子孙节点. .descendants 属性可以对所有tag的子孙节点进行递归循环 [5] :

-
for child in head_tag.descendants:
-    print(child)
-    # <title>The Dormouse's story</title>
-    # The Dormouse's story
-
-
-

上面的例子中, <head>标签只有一个子节点,但是有2个子孙节点:<head>节点和<head>的子节点, BeautifulSoup 有一个直接子节点(<html>节点),却有很多子孙节点:

-
len(list(soup.children))
-# 1
-len(list(soup.descendants))
-# 25
-
-
-
-
-

.string

-

如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点:

-
title_tag.string
-# u'The Dormouse's story'
-
-
-

如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同:

-
head_tag.contents
-# [<title>The Dormouse's story</title>]
-
-head_tag.string
-# u'The Dormouse's story'
-
-
-

如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None :

-
print(soup.html.string)
-# None
-
-
-
-
-

.strings 和 stripped_strings

-

如果tag中包含多个字符串 [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'...'
-
-
-

全部是空格的行会被忽略掉,段首和段末的空白会被删除

-
-
-
-

父节点

-

继续分析文档树,每个tag或字符串都有父节点:被包含在某个tag中

-
-

.parent

-

通过 .parent 属性来获取某个元素的父节点.在例子“爱丽丝”的文档中,<head>标签是<title>标签的父节点:

-
title_tag = soup.title
-title_tag
-# <title>The Dormouse's story</title>
-title_tag.parent
-# <head><title>The Dormouse's story</title></head>
-
-
-

文档title的字符串也有父节点:<title>标签

-
title_tag.string.parent
-# <title>The Dormouse's story</title>
-
-
-

文档的顶层节点比如<html>的父节点是 BeautifulSoup 对象:

-
html_tag = soup.html
-type(html_tag.parent)
-# <class 'bs4.BeautifulSoup'>
-
-
-

BeautifulSoup 对象的 .parent 是None:

-
print(soup.parent)
-# None
-
-
-
-
-

.parents

-

通过元素的 .parents 属性可以递归得到元素的所有父辈节点,下面的例子使用了 .parents 方法遍历了<a>标签到根节点的所有节点.

-
link = soup.a
-link
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-for parent in link.parents:
-    if parent is None:
-        print(parent)
-    else:
-        print(parent.name)
-# p
-# body
-# html
-# [document]
-# None
-
-
-
-
-
-

兄弟节点

-

看一段简单的例子:

-
sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
-print(sibling_soup.prettify())
-# <html>
-#  <body>
-#   <a>
-#    <b>
-#     text1
-#    </b>
-#    <c>
-#     text2
-#    </c>
-#   </a>
-#  </body>
-# </html>
-
-
-

因为<b>标签和<c>标签是同一层:他们是同一个元素的子节点,所以<b>和<c>可以被称为兄弟节点.一段文档以标准格式输出时,兄弟节点有相同的缩进级别.在代码中也可以使用这种关系.

-
-

.next_sibling 和 .previous_sibling

-

在文档树中,使用 .next_sibling.previous_sibling 属性来查询兄弟节点:

-
sibling_soup.b.next_sibling
-# <c>text2</c>
-
-sibling_soup.c.previous_sibling
-# <b>text1</b>
-
-
-

<b>标签有 .next_sibling 属性,但是没有 .previous_sibling 属性,因为<b>标签在同级节点中是第一个.同理,<c>标签有 .previous_sibling 属性,却没有 .next_sibling 属性:

-
print(sibling_soup.b.previous_sibling)
-# None
-print(sibling_soup.c.next_sibling)
-# None
-
-
-

例子中的字符串“text1”和“text2”不是兄弟节点,因为它们的父节点不同:

-
sibling_soup.b.string
-# u'text1'
-
-print(sibling_soup.b.string.next_sibling)
-# None
-
-
-

实际文档中的tag的 .next_sibling.previous_sibling 属性通常是字符串或空白. 看看“爱丽丝”文档:

-
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
-<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
-<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
-
-

如果以为第一个<a>标签的 .next_sibling 结果是第二个<a>标签,那就错了,真实结果是第一个<a>标签和第二个<a>标签之间的顿号和换行符:

-
link = soup.a
-link
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-link.next_sibling
-# u',\n'
-
-
-

第二个<a>标签是顿号的 .next_sibling 属性:

-
link.next_sibling.next_sibling
-# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
-
-
-
-
-

.next_siblings 和 .previous_siblings

-

通过 .next_siblings.previous_siblings 属性可以对当前节点的兄弟节点迭代输出:

-
for sibling in soup.a.next_siblings:
-    print(repr(sibling))
-    # u',\n'
-    # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
-    # u' and\n'
-    # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
-    # u'; and they lived at the bottom of a well.'
-    # None
-
-for sibling in soup.find(id="link3").previous_siblings:
-    print(repr(sibling))
-    # ' and\n'
-    # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
-    # u',\n'
-    # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-    # u'Once upon a time there were three little sisters; and their names were\n'
-    # None
-
-
-
-
-
-

回退和前进

-

看一下“爱丽丝” 文档:

-
<html><head><title>The Dormouse's story</title></head>
-<p class="title"><b>The Dormouse's story</b></p>
-
-

HTML解析器把这段字符串转换成一连串的事件: “打开<html>标签”,”打开一个<head>标签”,”打开一个<title>标签”,”添加一段字符串”,”关闭<title>标签”,”打开<p>标签”,等等.Beautiful Soup提供了重现解析器初始化过程的方法.

-
-

.next_element 和 .previous_element

-

.next_element 属性指向解析过程中下一个被解析的对象(字符串或tag),结果可能与 .next_sibling 相同,但通常是不一样的.

-

这是“爱丽丝”文档中最后一个<a>标签,它的 .next_sibling 结果是一个字符串,因为当前的解析过程 [2] 因为当前的解析过程因为遇到了<a>标签而中断了:

-
last_a_tag = soup.find("a", id="link3")
-last_a_tag
-# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
-
-last_a_tag.next_sibling
-# '; and they lived at the bottom of a well.'
-
-
-

但这个<a>标签的 .next_element 属性结果是在<a>标签被解析之后的解析内容,不是<a>标签后的句子部分,应该是字符串”Tillie”:

-
last_a_tag.next_element
-# u'Tillie'
-
-
-

这是因为在原始文档中,字符串“Tillie” 在分号前出现,解析器先进入<a>标签,然后是字符串“Tillie”,然后关闭</a>标签,然后是分号和剩余部分.分号与<a>标签在同一层级,但是字符串“Tillie”会被先解析.

-

.previous_element 属性刚好与 .next_element 相反,它指向当前被解析的对象的前一个解析对象:

-
last_a_tag.previous_element
-# u' and\n'
-last_a_tag.previous_element.next_element
-# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
-
-
-
-
-

.next_elements 和 .previous_elements

-

通过 .next_elements.previous_elements 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样:

-
for element in last_a_tag.next_elements:
-    print(repr(element))
-# u'Tillie'
-# u';\nand they lived at the bottom of a well.'
-# u'\n\n'
-# <p class="story">...</p>
-# u'...'
-# u'\n'
-# None
-
-
-
-
-
-
-

搜索文档树

-

Beautiful Soup定义了很多搜索方法,这里着重介绍2个: find()find_all() .其它方法的参数和用法类似,请读者举一反三.

-

再以“爱丽丝”文档作为例子:

-
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)
-
-
-

使用 find_all() 类似的方法可以查找到想要查找的文档内容

-
-

过滤器

-

介绍 find_all() 方法前,先介绍一下过滤器的类型 [3] ,这些过滤器贯穿整个搜索的API.过滤器可以被用在tag的name中,节点的属性中,字符串中或他们的混合中.

-
-

字符串

-

最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签:

-
soup.find_all('b')
-# [<b>The Dormouse's story</b>]
-
-
-

如果传入字节码参数,Beautiful Soup会当作UTF-8编码,可以传入一段Unicode 编码来避免Beautiful Soup解析编码出错

-
-
-

正则表达式

-

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到:

-
import re
-for tag in soup.find_all(re.compile("^b")):
-    print(tag.name)
-# body
-# b
-
-
-

下面代码找出所有名字中包含”t”的标签:

-
for tag in soup.find_all(re.compile("t")):
-    print(tag.name)
-# html
-# title
-
-
-
-
-

列表

-

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签:

-
soup.find_all(["a", "b"])
-# [<b>The Dormouse's story</b>,
-#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-
-
-

True

-

True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

-
for tag in soup.find_all(True):
-    print(tag.name)
-# html
-# head
-# title
-# body
-# p
-# b
-# p
-# a
-# a
-# a
-# p
-
-
-
-
-

方法

-

如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False

-

下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:

-
def has_class_but_no_id(tag):
-    return tag.has_attr('class') and not tag.has_attr('id')
-
-
-

将这个方法作为参数传入 find_all() 方法,将得到所有<p>标签:

-
soup.find_all(has_class_but_no_id)
-# [<p class="title"><b>The Dormouse's story</b></p>,
-#  <p class="story">Once upon a time there were...</p>,
-#  <p class="story">...</p>]
-
-
-

返回结果中只有<p>标签没有<a>标签,因为<a>标签还定义了”id”,没有返回<html>和<head>,因为<html>和<head>中没有定义”class”属性.

-

下面代码找到所有被文字包含的节点内容:

-
from bs4 import NavigableString
-def surrounded_by_strings(tag):
-    return (isinstance(tag.next_element, NavigableString)
-            and isinstance(tag.previous_element, NavigableString))
-
-for tag in soup.find_all(surrounded_by_strings):
-    print tag.name
-# p
-# a
-# a
-# a
-# p
-
-
-

现在来了解一下搜索方法的细节

-
-
-
-

find_all()

-

find_all( name , attrs , recursive , text , **kwargs )

-

find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件.这里有几个例子:

-
soup.find_all("title")
-# [<title>The Dormouse's story</title>]
-
-soup.find_all("p", "title")
-# [<p class="title"><b>The Dormouse's story</b></p>]
-
-soup.find_all("a")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.find_all(id="link2")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-import re
-soup.find(text=re.compile("sisters"))
-# u'Once upon a time there were three little sisters; and their names were\n'
-
-
-

有几个方法很相似,还有几个方法是新的,参数中的 textid 是什么含义? 为什么 find_all("p", "title") 返回的是CSS Class为”title”的<p>标签? 我们来仔细看一下 find_all() 的参数

-
-

name 参数

-

name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.

-

简单的用法如下:

-
soup.find_all("title")
-# [<title>The Dormouse's story</title>]
-
-
-

重申: 搜索 name 参数的值可以使任一类型的 过滤器 ,字符窜,正则表达式,列表,方法或是 True .

-
-
-

keyword 参数

-

如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.

-
soup.find_all(id='link2')
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-
-

如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性:

-
soup.find_all(href=re.compile("elsie"))
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-
-

搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True .

-

下面的例子在文档树中查找所有包含 id 属性的tag,无论 id 的值是什么:

-
soup.find_all(id=True)
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-

使用多个指定名字的参数可以同时过滤tag的多个属性:

-
soup.find_all(href=re.compile("elsie"), id='link1')
-# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
-
-
-

有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:

-
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
-data_soup.find_all(data-foo="value")
-# SyntaxError: keyword can't be an expression
-
-
-

但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:

-
data_soup.find_all(attrs={"data-foo": "value"})
-# [<div data-foo="value">foo!</div>]
-
-
-
-
-

按CSS搜索

-

按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag:

-
soup.find_all("a", class_="sister")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-

class_ 参数同样接受不同类型的 过滤器 ,字符串,正则表达式,方法或 True :

-
soup.find_all(class_=re.compile("itl"))
-# [<p class="title"><b>The Dormouse's story</b></p>]
-
-def has_six_characters(css_class):
-    return css_class is not None and len(css_class) == 6
-
-soup.find_all(class_=has_six_characters)
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-

tag的 class 属性是 多值属性 .按照CSS类名搜索tag时,可以分别搜索tag中的每个CSS类名:

-
css_soup = BeautifulSoup('<p class="body strikeout"></p>')
-css_soup.find_all("p", class_="strikeout")
-# [<p class="body strikeout"></p>]
-
-css_soup.find_all("p", class_="body")
-# [<p class="body strikeout"></p>]
-
-
-

搜索 class 属性时也可以通过CSS值完全匹配:

-
css_soup.find_all("p", class_="body strikeout")
-# [<p class="body strikeout"></p>]
-
-
-

完全匹配 class 的值时,如果CSS类名的顺序与实际不符,将搜索不到结果:

-
soup.find_all("a", attrs={"class": "sister"})
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-
-
-

text 参数

-

通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True . 看例子:

-
soup.find_all(text="Elsie")
-# [u'Elsie']
-
-soup.find_all(text=["Tillie", "Elsie", "Lacie"])
-# [u'Elsie', u'Lacie', u'Tillie']
-
-soup.find_all(text=re.compile("Dormouse"))
-[u"The Dormouse's story", u"The Dormouse's story"]
-
-def is_the_only_string_within_a_tag(s):
-    ""Return True if this string is the only child of its parent tag.""
-    return (s == s.parent.string)
-
-soup.find_all(text=is_the_only_string_within_a_tag)
-# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']
-
-

虽然 text 参数用于搜索字符串,还可以与其它参数混合使用来过滤tag.Beautiful Soup会找到 .string 方法与 text 参数值相符的tag.下面代码用来搜索内容里面包含“Elsie”的<a>标签:

-
soup.find_all("a", text="Elsie")
-# [<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>]
-
-
-
-
-

limit 参数

-

find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

-

文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量:

-
soup.find_all("a", limit=2)
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-
-
-
-

recursive 参数

-

调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

-

一段简单的文档:

-
<html>
- <head>
-  <title>
-   The Dormouse's story
-  </title>
- </head>
-...
-
-

是否使用 recursive 参数的搜索结果:

-
soup.html.find_all("title")
-# [<title>The Dormouse's story</title>]
-
-soup.html.find_all("title", recursive=False)
-# []
-
-
-
-
-
-

像调用 find_all() 一样调用tag

-

find_all() 几乎是Beautiful Soup中最常用的搜索方法,所以我们定义了它的简写方法. BeautifulSoup 对象和 tag 对象可以被当作一个方法来使用,这个方法的执行结果与调用这个对象的 find_all() 方法相同,下面两行代码是等价的:

-
soup.find_all("a")
-soup("a")
-
-
-

这两行代码也是等价的:

-
soup.title.find_all(text=True)
-soup.title(text=True)
-
-
-
-
-

find()

-

find( name , attrs , recursive , text , **kwargs )

-

find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个<body>标签,那么使用 find_all() 方法来查找<body>标签就不太合适, 使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.下面两行代码是等价的:

-
soup.find_all('title', limit=1)
-# [<title>The Dormouse's story</title>]
-
-soup.find('title')
-# <title>The Dormouse's story</title>
-
-
-

唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.

-

find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .

-
print(soup.find("nosuchtag"))
-# None
-
-
-

soup.head.titletag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:

-
soup.head.title
-# <title>The Dormouse's story</title>
-
-soup.find("head").find("title")
-# <title>The Dormouse's story</title>
-
-
-
-
-

find_parents() 和 find_parent()

-

find_parents( name , attrs , recursive , text , **kwargs )

-

find_parent( name , attrs , recursive , text , **kwargs )

-

我们已经用了很大篇幅来介绍 find_all()find() 方法,Beautiful Soup中还有10个用于搜索的API.它们中的五个用的是与 find_all() 相同的搜索参数,另外5个与 find() 方法的搜索参数类似.区别仅是它们搜索文档的不同部分.

-

记住: find_all()find() 只搜索当前节点的所有子节点,孙子节点等. find_parents()find_parent() 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容. 我们从一个文档中的一个叶子节点开始:

-
a_string = soup.find(text="Lacie")
-a_string
-# u'Lacie'
-
-a_string.find_parents("a")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-a_string.find_parent("p")
-# <p class="story">Once upon a time there were three little sisters; and their names were
-#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
-#  and they lived at the bottom of a well.</p>
-
-a_string.find_parents("p", class="title")
-# []
-
-

文档中的一个<a>标签是是当前叶子节点的直接父节点,所以可以被找到.还有一个<p>标签,是目标叶子节点的间接父辈节点,所以也可以被找到.包含class值为”title”的<p>标签不是不是目标叶子节点的父辈节点,所以通过 find_parents() 方法搜索不到.

-

find_parent()find_parents() 方法会让人联想到 .parent.parents 属性.它们之间的联系非常紧密.搜索父辈节点的方法实际上就是对 .parents 属性的迭代搜索.

-
-
-

find_next_siblings() 合 find_next_sibling()

-

find_next_siblings( name , attrs , recursive , text , **kwargs )

-

find_next_sibling( name , attrs , recursive , text , **kwargs )

-

这2个方法通过 .next_siblings 属性对当tag的所有后面解析 [5] 的兄弟tag节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点, find_next_sibling() 只返回符合条件的后面的第一个tag节点.

-
first_link = soup.a
-first_link
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-first_link.find_next_siblings("a")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-first_story_paragraph = soup.find("p", "story")
-first_story_paragraph.find_next_sibling("p")
-# <p class="story">...</p>
-
-
-
-
-

find_previous_siblings() 和 find_previous_sibling()

-

find_previous_siblings( name , attrs , recursive , text , **kwargs )

-

find_previous_sibling( name , attrs , recursive , text , **kwargs )

-

这2个方法通过 .previous_siblings 属性对当前tag的前面解析 [5] 的兄弟tag节点进行迭代, find_previous_siblings() 方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点:

-
last_link = soup.find("a", id="link3")
-last_link
-# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
-
-last_link.find_previous_siblings("a")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-first_story_paragraph = soup.find("p", "story")
-first_story_paragraph.find_previous_sibling("p")
-# <p class="title"><b>The Dormouse's story</b></p>
-
-
-
-
-

find_all_next() 和 find_next()

-

find_all_next( name , attrs , recursive , text , **kwargs )

-

find_next( name , attrs , recursive , text , **kwargs )

-

这2个方法通过 .next_elements 属性对当前tag的之后的 [5] tag和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点:

-
first_link = soup.a
-first_link
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-first_link.find_all_next(text=True)
-# [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']
-
-first_link.find_next("p")
-# <p class="story">...</p>
-
-
-

第一个例子中,字符串 “Elsie”也被显示出来,尽管它被包含在我们开始查找的<a>标签的里面.第二个例子中,最后一个<p>标签也被显示出来,尽管它与我们开始查找位置的<a>标签不属于同一部分.例子中,搜索的重点是要匹配过滤器的条件,并且在文档中出现的顺序而不是开始查找的元素的位置.

-
-
-

find_all_previous() 和 find_previous()

-

find_all_previous( name , attrs , recursive , text , **kwargs )

-

find_previous( name , attrs , recursive , text , **kwargs )

-

这2个方法通过 .previous_elements 属性对当前节点前面 [5] 的tag和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous() 方法返回第一个符合条件的节点.

-
first_link = soup.a
-first_link
-# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
-
-first_link.find_all_previous("p")
-# [<p class="story">Once upon a time there were three little sisters; ...</p>,
-#  <p class="title"><b>The Dormouse's story</b></p>]
-
-first_link.find_previous("title")
-# <title>The Dormouse's story</title>
-
-
-

find_all_previous("p") 返回了文档中的第一段(class=”title”的那段),但还返回了第二段,<p>标签包含了我们开始查找的<a>标签.不要惊讶,这段代码的功能是查找所有出现在指定<a>标签之前的<p>标签,因为这个<p>标签包含了开始的<a>标签,所以<p>标签一定是在<a>之前出现的.

-
-
-

CSS选择器

-

Beautiful Soup支持大部分的CSS选择器 [6] ,在 TagBeautifulSoup 对象的 .select() 方法中传入字符串参数,即可使用CSS选择器的语法找到tag:

-
soup.select("title")
-# [<title>The Dormouse's story</title>]
-
-soup.select("p nth-of-type(3)")
-# [<p class="story">...</p>]
-
-
-

通过tag标签逐层查找:

-
soup.select("body a")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.select("html head title")
-# [<title>The Dormouse's story</title>]
-
-
-

找到某个tag标签下的直接子标签 [6] :

-
soup.select("head > title")
-# [<title>The Dormouse's story</title>]
-
-soup.select("p > a")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie"  id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.select("p > a:nth-of-type(2)")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-soup.select("p > #link1")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-soup.select("body > a")
-# []
-
-
-

找到兄弟节点标签:

-
soup.select("#link1 ~ .sister")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie"  id="link3">Tillie</a>]
-
-soup.select("#link1 + .sister")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-
-

通过CSS的类名查找:

-
soup.select(".sister")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.select("[class~=sister]")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-

通过tag的id查找:

-
soup.select("#link1")
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-soup.select("a#link2")
-# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
-
-
-

通过是否存在某个属性来查找:

-
soup.select('a[href]')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-
-

通过属性的值来查找:

-
soup.select('a[href="http://example.com/elsie"]')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-soup.select('a[href^="http://example.com/"]')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
-#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
-#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.select('a[href$="tillie"]')
-# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
-
-soup.select('a[href*=".com/el"]')
-# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
-
-
-

通过语言设置来查找:

-
multilingual_markup = """
- <p lang="en">Hello</p>
- <p lang="en-us">Howdy, y'all</p>
- <p lang="en-gb">Pip-pip, old fruit</p>
- <p lang="fr">Bonjour mes amis</p>
-"""
-multilingual_soup = BeautifulSoup(multilingual_markup)
-multilingual_soup.select('p[lang|=en]')
-# [<p lang="en">Hello</p>,
-#  <p lang="en-us">Howdy, y'all</p>,
-#  <p lang="en-gb">Pip-pip, old fruit</p>]
-
-
-

对于熟悉CSS选择器语法的人来说这是个非常方便的方法.Beautiful Soup也支持CSS选择器API,如果你仅仅需要CSS选择器的功能,那么直接使用 lxml 也可以,而且速度更快,支持更多的CSS选择器语法,但Beautiful Soup整合了CSS选择器的语法和自身方便使用API.

-
-
-
-

修改文档树

-

Beautiful Soup的强项是文档树的搜索,但同时也可以方便的修改文档树

-
-

修改tag的名称和属性

-

Attributes 的章节中已经介绍过这个功能,但是再看一遍也无妨. 重命名一个tag,改变属性的值,添加或删除属性:

-
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
-tag = soup.b
-
-tag.name = "blockquote"
-tag['class'] = 'verybold'
-tag['id'] = 1
-tag
-# <blockquote class="verybold" id="1">Extremely bold</blockquote>
-
-del tag['class']
-del tag['id']
-tag
-# <blockquote>Extremely bold</blockquote>
-
-
-
-
-

修改 .string

-

给tag的 .string 属性赋值,就相当于用当前的内容替代了原来的内容:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-
-tag = soup.a
-tag.string = "New link text."
-tag
-# <a href="http://example.com/">New link text.</a>
-
-
-

注意: 如果当前的tag包含了其它tag,那么给它的 .string 属性赋值会覆盖掉原有的所有内容包括子tag

-
-
-

append()

-

Tag.append() 方法想tag中添加内容,就好像Python的列表的 .append() 方法:

-
soup = BeautifulSoup("<a>Foo</a>")
-soup.a.append("Bar")
-
-soup
-# <html><head></head><body><a>FooBar</a></body></html>
-soup.a.contents
-# [u'Foo', u'Bar']
-
-
-
-
-

BeautifulSoup.new_string() 和 .new_tag()

-

如果想添加一段文本内容到文档中也没问题,可以调用Python的 append() 方法或调用工厂方法 BeautifulSoup.new_string() :

-
soup = BeautifulSoup("<b></b>")
-tag = soup.b
-tag.append("Hello")
-new_string = soup.new_string(" there")
-tag.append(new_string)
-tag
-# <b>Hello there.</b>
-tag.contents
-# [u'Hello', u' there']
-
-
-

如果想要创建一段注释,或 NavigableString 的任何子类,将子类作为 new_string() 方法的第二个参数传入:

-
from bs4 import Comment
-new_comment = soup.new_string("Nice to see you.", Comment)
-tag.append(new_comment)
-tag
-# <b>Hello there<!--Nice to see you.--></b>
-tag.contents
-# [u'Hello', u' there', u'Nice to see you.']
-
-
-

# 这是Beautiful Soup 4.2.1 中新增的方法

-

创建一个tag最好的方法是调用工厂方法 BeautifulSoup.new_tag() :

-
soup = BeautifulSoup("<b></b>")
-original_tag = soup.b
-
-new_tag = soup.new_tag("a", href="http://www.example.com")
-original_tag.append(new_tag)
-original_tag
-# <b><a href="http://www.example.com"></a></b>
-
-new_tag.string = "Link text."
-original_tag
-# <b><a href="http://www.example.com">Link text.</a></b>
-
-
-

第一个参数作为tag的name,是必填,其它参数选填

-
-
-

insert()

-

Tag.insert() 方法与 Tag.append() 方法类似,区别是不会把新元素添加到父节点 .contents 属性的最后,而是把元素插入到指定的位置.与Python列表总的 .insert() 方法的用法下同:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-tag = soup.a
-
-tag.insert(1, "but did not endorse ")
-tag
-# <a href="http://example.com/">I linked to but did not endorse <i>example.com</i></a>
-tag.contents
-# [u'I linked to ', u'but did not endorse', <i>example.com</i>]
-
-
-
-
-

insert_before() 和 insert_after()

-

insert_before() 方法在当前tag或文本节点前插入内容:

-
soup = BeautifulSoup("<b>stop</b>")
-tag = soup.new_tag("i")
-tag.string = "Don't"
-soup.b.string.insert_before(tag)
-soup.b
-# <b><i>Don't</i>stop</b>
-
-
-

insert_after() 方法在当前tag或文本节点后插入内容:

-
soup.b.i.insert_after(soup.new_string(" ever "))
-soup.b
-# <b><i>Don't</i> ever stop</b>
-soup.b.contents
-# [<i>Don't</i>, u' ever ', u'stop']
-
-
-
-
-

clear()

-

Tag.clear() 方法移除当前tag的内容:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-tag = soup.a
-
-tag.clear()
-tag
-# <a href="http://example.com/"></a>
-
-
-
-
-

extract()

-

PageElement.extract() 方法将当前tag移除文档树,并作为方法结果返回:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-a_tag = soup.a
-
-i_tag = soup.i.extract()
-
-a_tag
-# <a href="http://example.com/">I linked to</a>
-
-i_tag
-# <i>example.com</i>
-
-print(i_tag.parent)
-None
-
-
-

这个方法实际上产生了2个文档树: 一个是用来解析原始文档的 BeautifulSoup 对象,另一个是被移除并且返回的tag.被移除并返回的tag可以继续调用 extract 方法:

-
my_string = i_tag.string.extract()
-my_string
-# u'example.com'
-
-print(my_string.parent)
-# None
-i_tag
-# <i></i>
-
-
-
-
-

decompose()

-

Tag.decompose() 方法将当前节点移除文档树并完全销毁:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-a_tag = soup.a
-
-soup.i.decompose()
-
-a_tag
-# <a href="http://example.com/">I linked to</a>
-
-
-
-
-

replace_with()

-

PageElement.replace_with() 方法移除文档树中的某段内容,并用新tag或文本节点替代它:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-a_tag = soup.a
-
-new_tag = soup.new_tag("b")
-new_tag.string = "example.net"
-a_tag.i.replace_with(new_tag)
-
-a_tag
-# <a href="http://example.com/">I linked to <b>example.net</b></a>
-
-
-

replace_with() 方法返回被替代的tag或文本节点,可以用来浏览或添加到文档树其它地方

-
-
-

wrap()

-

PageElement.wrap() 方法可以对指定的tag元素进行包装 [8] ,并返回包装后的结果:

-
soup = BeautifulSoup("<p>I wish I was bold.</p>")
-soup.p.string.wrap(soup.new_tag("b"))
-# <b>I wish I was bold.</b>
-
-soup.p.wrap(soup.new_tag("div"))
-# <div><p><b>I wish I was bold.</b></p></div>
-
-
-

该方法在 Beautiful Soup 4.0.5 中添加

-
-
-

unwrap()

-

Tag.unwrap() 方法与 wrap() 方法相反.将移除tag内的所有tag标签,该方法常被用来进行标记的解包:

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-a_tag = soup.a
-
-a_tag.i.unwrap()
-a_tag
-# <a href="http://example.com/">I linked to example.com</a>
-
-
-

replace_with() 方法相同, unwrap() 方法返回被移除的tag

-
-
-
-

输出

-
-

格式化输出

-

prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行

-
markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
-soup = BeautifulSoup(markup)
-soup.prettify()
-# '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/">\n...'
-
-print(soup.prettify())
-# <html>
-#  <head>
-#  </head>
-#  <body>
-#   <a href="http://example.com/">
-#    I linked to
-#    <i>
-#     example.com
-#    </i>
-#   </a>
-#  </body>
-# </html>
-
-
-

BeautifulSoup 对象和它的tag节点都可以调用 prettify() 方法:

-
print(soup.a.prettify())
-# <a href="http://example.com/">
-#  I linked to
-#  <i>
-#   example.com
-#  </i>
-# </a>
-
-
-
-
-

压缩输出

-

如果只想得到结果字符串,不重视格式,那么可以对一个 BeautifulSoup 对象或 Tag 对象使用Python的 unicode()str() 方法:

-
str(soup)
-# '<html><head></head><body><a href="http://example.com/">I linked to <i>example.com</i></a></body></html>'
-
-unicode(soup.a)
-# u'<a href="http://example.com/">I linked to <i>example.com</i></a>'
-
-
-

str() 方法返回UTF-8编码的字符串,可以指定 编码 的设置.

-

还可以调用 encode() 方法获得字节码或调用 decode() 方法获得Unicode.

-
-
-

输出格式

-

Beautiful Soup输出是会将HTML中的特殊字符转换成Unicode,比如“&lquot;”:

-
soup = BeautifulSoup("&ldquo;Dammit!&rdquo; he said.")
-unicode(soup)
-# u'<html><head></head><body>\u201cDammit!\u201d he said.</body></html>'
-
-
-

如果将文档转换成字符串,Unicode编码会被编码成UTF-8.这样就无法正确显示HTML特殊字符了:

-
str(soup)
-# '<html><head></head><body>\xe2\x80\x9cDammit!\xe2\x80\x9d he said.</body></html>'
-
-
-
-
-

get_text()

-

如果只想得到tag中包含的文本内容,那么可以嗲用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:

-
markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
-soup = BeautifulSoup(markup)
-
-soup.get_text()
-u'\nI linked to example.com\n'
-soup.i.get_text()
-u'example.com'
-
-
-

可以通过参数指定tag的文本内容的分隔符:

-
# soup.get_text("|")
-u'\nI linked to |example.com|\n'
-
-
-

还可以去除获得文本内容的前后空白:

-
# soup.get_text("|", strip=True)
-u'I linked to|example.com'
-
-
-

或者使用 .stripped_strings 生成器,获得文本列表后手动处理列表:

-
[text for text in soup.stripped_strings]
-# [u'I linked to', u'example.com']
-
-
-
-
-
-

指定文档解析器

-

如果仅是想要解析HTML文档,只要用文档创建 BeautifulSoup 对象就可以了.Beautiful Soup会自动选择一个解析器来解析文档.但是还可以通过参数指定使用那种解析器来解析当前文档.

-

BeautifulSoup 第一个参数应该是要被解析的文档字符串或是文件句柄,第二个参数用来标识怎样解析文档.如果第二个参数为空,那么Beautiful Soup根据当前系统安装的库自动选择解析器,解析器的优先数序: lxml, html5lib, Python标准库.在下面两种条件下解析器优先顺序会变化:

-
-
    -
  • 要解析的文档是什么类型: 目前支持, “html”, “xml”, 和 “html5”
  • -
  • 指定使用哪种解析器: 目前支持, “lxml”, “html5lib”, 和 “html.parser”
  • -
-
-

安装解析器 章节介绍了可以使用哪种解析器,以及如何安装.

-

如果指定的解析器没有安装,Beautiful Soup会自动选择其它方案.目前只有 lxml 解析器支持XML文档的解析,在没有安装lxml库的情况下,创建 beautifulsoup 对象时无论是否指定使用lxml,都无法得到解析后的对象

-
-

解析器之间的区别

-

Beautiful Soup为不同的解析器提供了相同的接口,但解析器本身时有区别的.同一篇文档被不同的解析器解析后可能会生成不同结构的树型文档.区别最大的是HTML解析器和XML解析器,看下面片段被解析成HTML结构:

-
BeautifulSoup("<a><b /></a>")
-# <html><head></head><body><a><b></b></a></body></html>
-
-
-

因为空标签<b />不符合HTML标准,所以解析器把它解析成<b></b>

-

同样的文档使用XML解析如下(解析XML需要安装lxml库).注意,空标签<b />依然被保留,并且文档前添加了XML头,而不是被包含在<html>标签内:

-
BeautifulSoup("<a><b /></a>", "xml")
-# <?xml version="1.0" encoding="utf-8"?>
-# <a><b/></a>
-
-
-

HTML解析器之间也有区别,如果被解析的HTML文档是标准格式,那么解析器之间没有任何差别,只是解析速度不同,结果都会返回正确的文档树.

-

但是如果被解析文档不是标准格式,那么不同的解析器返回结果可能不同.下面例子中,使用lxml解析错误格式的文档,结果</p>标签被直接忽略掉了:

-
BeautifulSoup("<a></p>", "lxml")
-# <html><body><a></a></body></html>
-
-
-

使用html5lib库解析相同文档会得到不同的结果:

-
BeautifulSoup("<a></p>", "html5lib")
-# <html><head></head><body><a><p></p></a></body></html>
-
-
-

html5lib库没有忽略掉</p>标签,而是自动补全了标签,还给文档树添加了<head>标签.

-

使用pyhton内置库解析结果如下:

-
BeautifulSoup("<a></p>", "html.parser")
-# <a></a>
-
-
-

与lxml [7] 库类似的,Python内置库忽略掉了</p>标签,与html5lib库不同的是标准库没有尝试创建符合标准的文档格式或将文档片段包含在<body>标签内,与lxml不同的是标准库甚至连<html>标签都没有尝试去添加.

-

因为文档片段“<a></p>”是错误格式,所以以上解析方式都能算作”正确”,html5lib库使用的是HTML5的部分标准,所以最接近”正确”.不过所有解析器的结构都能够被认为是”正常”的.

-

不同的解析器可能影响代码执行结果,如果在分发给别人的代码中使用了 BeautifulSoup ,那么最好注明使用了哪种解析器,以减少不必要的麻烦.

-
-
-
-

编码

-

任何HTML或XML文档都有自己的编码方式,比如ASCII 或 UTF-8,但是使用Beautiful Soup解析后,文档都被转换成了Unicode:

-
markup = "<h1>Sacr\xc3\xa9 bleu!</h1>"
-soup = BeautifulSoup(markup)
-soup.h1
-# <h1>Sacré bleu!</h1>
-soup.h1.string
-# u'Sacr\xe9 bleu!'
-
-
-

这不是魔术(但很神奇),Beautiful Soup用了 编码自动检测 子库来识别当前文档编码并转换成Unicode编码. BeautifulSoup 对象的 .original_encoding 属性记录了自动识别编码的结果:

-
soup.original_encoding
-'utf-8'
-
-
-

编码自动检测 功能大部分时候都能猜对编码格式,但有时候也会出错.有时候即使猜测正确,也是在逐个字节的遍历整个文档后才猜对的,这样很慢.如果预先知道文档编码,可以设置编码参数来减少自动检查编码出错的概率并且提高文档解析速度.在创建 BeautifulSoup 对象的时候设置 from_encoding 参数.

-

下面一段文档用了ISO-8859-8编码方式,这段文档太短,结果Beautiful Soup以为文档是用ISO-8859-7编码:

-
markup = b"<h1>\xed\xe5\xec\xf9</h1>"
-soup = BeautifulSoup(markup)
-soup.h1
-<h1>νεμω</h1>
-soup.original_encoding
-'ISO-8859-7'
-
-

通过传入 from_encoding 参数来指定编码方式:

-
soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
-soup.h1
-<h1>םולש</h1>
-soup.original_encoding
-'iso8859-8'
-
-

少数情况下(通常是UTF-8编码的文档中包含了其它编码格式的文件),想获得正确的Unicode编码就不得不将文档中少数特殊编码字符替换成特殊Unicode编码,“REPLACEMENT CHARACTER” (U+FFFD, �) [9] . 如果Beautifu Soup猜测文档编码时作了特殊字符的替换,那么Beautiful Soup会把 UnicodeDammitBeautifulSoup 对象的 .contains_replacement_characters 属性标记为 True .这样就可以知道当前文档进行Unicode编码后丢失了一部分特殊内容字符.如果文档中包含�而 .contains_replacement_characters 属性是 False ,则表示�就是文档中原来的字符,不是转码失败.

-
-

输出编码

-

通过Beautiful Soup输出文档时,不管输入文档是什么编码方式,输出编码均为UTF-8编码,下面例子输入文档是Latin-1编码:

-
markup = b'''
-<html>
-  <head>
-    <meta content="text/html; charset=ISO-Latin-1" http-equiv="Content-type" />
-  </head>
-  <body>
-    <p>Sacr\xe9 bleu!</p>
-  </body>
-</html>
-'''
-
-soup = BeautifulSoup(markup)
-print(soup.prettify())
-# <html>
-#  <head>
-#   <meta content="text/html; charset=utf-8" http-equiv="Content-type" />
-#  </head>
-#  <body>
-#   <p>
-#    Sacré bleu!
-#   </p>
-#  </body>
-# </html>
-
-
-

注意,输出文档中的<meta>标签的编码设置已经修改成了与输出编码一致的UTF-8.

-

如果不想用UTF-8编码输出,可以将编码方式传入 prettify() 方法:

-
print(soup.prettify("latin-1"))
-# <html>
-#  <head>
-#   <meta content="text/html; charset=latin-1" http-equiv="Content-type" />
-# ...
-
-
-

还可以调用 BeautifulSoup 对象或任意节点的 encode() 方法,就像Python的字符串调用 encode() 方法一样:

-
soup.p.encode("latin-1")
-# '<p>Sacr\xe9 bleu!</p>'
-
-soup.p.encode("utf-8")
-# '<p>Sacr\xc3\xa9 bleu!</p>'
-
-
-

如果文档中包含当前编码不支持的字符,那么这些字符将呗转换成一系列XML特殊字符引用,下面例子中包含了Unicode编码字符SNOWMAN:

-
markup = u"<b>\N{SNOWMAN}</b>"
-snowman_soup = BeautifulSoup(markup)
-tag = snowman_soup.b
-
-
-

SNOWMAN字符在UTF-8编码中可以正常显示(看上去像是☃),但有些编码不支持SNOWMAN字符,比如ISO-Latin-1或ASCII,那么在这些编码中SNOWMAN字符会被转换成“&#9731”:

-
print(tag.encode("utf-8"))
-# <b>☃</b>
-
-print tag.encode("latin-1")
-# <b>&#9731;</b>
-
-print tag.encode("ascii")
-# <b>&#9731;</b>
-
-
-
-
-

Unicode, dammit! (靠!)

-

编码自动检测 功能可以在Beautiful Soup以外使用,检测某段未知编码时,可以使用这个方法:

-
from bs4 import UnicodeDammit
-dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!")
-print(dammit.unicode_markup)
-# Sacré bleu!
-dammit.original_encoding
-# 'utf-8'
-
-
-

如果Python中安装了 chardetcchardet 那么编码检测功能的准确率将大大提高.输入的字符越多,检测结果越精确,如果事先猜测到一些可能编码,那么可以将猜测的编码作为参数,这样将优先检测这些编码:

-
dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"])
-print(dammit.unicode_markup)
-# Sacré bleu!
-dammit.original_encoding
-# 'latin-1'
-
-
-

编码自动检测 功能中有2项功能是Beautiful Soup库中用不到的

-
-

智能引号

-

使用Unicode时,Beautiful Soup还会智能的把引号 [10] 转换成HTML或XML中的特殊字符:

-
markup = b"<p>I just \x93love\x94 Microsoft Word\x92s smart quotes</p>"
-
-UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup
-# u'<p>I just &ldquo;love&rdquo; Microsoft Word&rsquo;s smart quotes</p>'
-
-UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup
-# u'<p>I just &#x201C;love&#x201D; Microsoft Word&#x2019;s smart quotes</p>'
-
-
-

也可以把引号转换为ASCII码:

-
UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup
-# u'<p>I just "love" Microsoft Word\'s smart quotes</p>'
-
-
-

很有用的功能,但是Beautiful Soup没有使用这种方式.默认情况下,Beautiful Soup把引号转换成Unicode:

-
UnicodeDammit(markup, ["windows-1252"]).unicode_markup
-# u'<p>I just \u201clove\u201d Microsoft Word\u2019s smart quotes</p>'
-
-
-
-
-

矛盾的编码

-

有时文档的大部分都是用UTF-8,但同时还包含了Windows-1252编码的字符,就像微软的智能引号 [10] 一样.一些包含多个信息的来源网站容易出现这种情况. UnicodeDammit.detwingle() 方法可以把这类文档转换成纯UTF-8编码格式,看个简单的例子:

-
snowmen = (u"\N{SNOWMAN}" * 3)
-quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}")
-doc = snowmen.encode("utf8") + quote.encode("windows_1252")
-
-
-

这段文档很杂乱,snowmen是UTF-8编码,引号是Windows-1252编码,直接输出时不能同时显示snowmen和引号,因为它们编码不同:

-
print(doc)
-# ☃☃☃�I like snowmen!�
-
-print(doc.decode("windows-1252"))
-# ☃☃☃“I like snowmen!”
-
-
-

如果对这段文档用UTF-8解码就会得到 UnicodeDecodeError 异常,如果用Windows-1252解码就回得到一堆乱码.幸好, UnicodeDammit.detwingle() 方法会吧这段字符串转换成UTF-8编码,允许我们同时显示出文档中的snowmen和引号:

-
new_doc = UnicodeDammit.detwingle(doc)
-print(new_doc.decode("utf8"))
-# ☃☃☃“I like snowmen!”
-
-
-

UnicodeDammit.detwingle() 方法只能解码包含在UTF-8编码中的Windows-1252编码内容,但这解决了最常见的一类问题.

-

在创建 BeautifulSoupUnicodeDammit 对象前一定要先对文档调用 UnicodeDammit.detwingle() 确保文档的编码方式正确.如果尝试去解析一段包含Windows-1252编码的UTF-8文档,就会得到一堆乱码,比如: ☃☃☃“I like snowmen!”.

-

UnicodeDammit.detwingle() 方法在Beautiful Soup 4.1.0版本中新增

-
-
-
-
-

解析部分文档

-

如果仅仅因为想要查找文档中的<a>标签而将整片文档进行解析,实在是浪费内存和时间.最快的方法是从一开始就把<a>标签以外的东西都忽略掉. SoupStrainer 类可以定义文档的某段内容,这样搜索文档时就不必先解析整篇文档,只会解析在 SoupStrainer 中定义过的文档. 创建一个 SoupStrainer 对象并作为 parse_only 参数给 BeautifulSoup 的构造方法即可.

-
-

SoupStrainer

-

SoupStrainer 类接受与典型搜索方法相同的参数:name , attrs , recursive , text , **kwargs 。下面举例说明三种 SoupStrainer 对象:

-
from bs4 import SoupStrainer
-
-only_a_tags = SoupStrainer("a")
-
-only_tags_with_id_link2 = SoupStrainer(id="link2")
-
-def is_short_string(string):
-    return len(string) < 10
-
-only_short_strings = SoupStrainer(text=is_short_string)
-
-
-

再拿“爱丽丝”文档来举例,来看看使用三种 SoupStrainer 对象做参数会有什么不同:

-
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>
-"""
-
-print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify())
-# <a class="sister" href="http://example.com/elsie" id="link1">
-#  Elsie
-# </a>
-# <a class="sister" href="http://example.com/lacie" id="link2">
-#  Lacie
-# </a>
-# <a class="sister" href="http://example.com/tillie" id="link3">
-#  Tillie
-# </a>
-
-print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify())
-# <a class="sister" href="http://example.com/lacie" id="link2">
-#  Lacie
-# </a>
-
-print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify())
-# Elsie
-# ,
-# Lacie
-# and
-# Tillie
-# ...
-#
-
-
-

还可以将 SoupStrainer 作为参数传入 搜索文档树 中提到的方法.这可能不是个常用用法,所以还是提一下:

-
soup = BeautifulSoup(html_doc)
-soup.find_all(only_short_strings)
-# [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie',
-#  u'\n\n', u'...', u'\n']
-
-
-
-
-
-

常见问题

-
-

代码诊断

-

如果想知道Beautiful Soup到底怎样处理一份文档,可以将文档传入 diagnose() 方法(Beautiful Soup 4.2.0中新增),Beautiful Soup会输出一份报告,说明不同的解析器会怎样处理这段文档,并标出当前的解析过程会使用哪种解析器:

-
from bs4.diagnose import diagnose
-data = open("bad.html").read()
-diagnose(data)
-
-# Diagnostic running on Beautiful Soup 4.2.0
-# Python version 2.7.3 (default, Aug  1 2012, 05:16:07)
-# I noticed that html5lib is not installed. Installing it may help.
-# Found lxml version 2.3.2.0
-#
-# Trying to parse your data with html.parser
-# Here's what html.parser did with the document:
-# ...
-
-
-

diagnose() 方法的输出结果可能帮助你找到问题的原因,如果不行,还可以把结果复制出来以便寻求他人的帮助

-
-
-

文档解析错误

-

文档解析错误有两种.一种是崩溃,Beautiful Soup尝试解析一段文档结果却抛除了异常,通常是 HTMLParser.HTMLParseError .还有一种异常情况,是Beautiful Soup解析后的文档树看起来与原来的内容相差很多.

-

这些错误几乎都不是Beautiful Soup的原因,这不会是因为Beautiful Soup得代码写的太优秀,而是因为Beautiful Soup没有包含任何文档解析代码.异常产生自被依赖的解析器,如果解析器不能很好的解析出当前的文档,那么最好的办法是换一个解析器.更多细节查看 安装解析器 章节.

-

最常见的解析错误是 HTMLParser.HTMLParseError: malformed start tagHTMLParser.HTMLParseError: bad end tag .这都是由Python内置的解析器引起的,解决方法是 安装lxml或html5lib

-

最常见的异常现象是当前文档找不到指定的Tag,而这个Tag光是用眼睛就足够发现的了. find_all() 方法返回 [] ,而 find() 方法返回 None .这是Python内置解析器的又一个问题: 解析器会跳过那些它不知道的tag.解决方法还是 安装lxml或html5lib

-
-
-

版本错误

-
    -
  • SyntaxError: Invalid syntax (异常位置在代码行: ROOT_TAG_NAME = u'[document]' ),因为Python2版本的代码没有经过迁移就在Python3中窒息感
  • -
  • ImportError: No module named HTMLParser 因为在Python3中执行Python2版本的Beautiful Soup
  • -
  • ImportError: No module named html.parser 因为在Python2中执行Python3版本的Beautiful Soup
  • -
  • ImportError: No module named BeautifulSoup 因为在没有安装BeautifulSoup3库的Python环境下执行代码,或忘记了BeautifulSoup4的代码需要从 bs4 包中引入
  • -
  • ImportError: No module named bs4 因为当前Python环境下还没有安装BeautifulSoup4
  • -
-
-
-

解析成XML

-

默认情况下,Beautiful Soup会将当前文档作为HTML格式解析,如果要解析XML文档,要在 BeautifulSoup 构造方法中加入第二个参数 “xml”:

-
soup = BeautifulSoup(markup, "xml")
-
-
-

当然,还需要 安装lxml

-
-
-

解析器的错误

-
    -
  • 如果同样的代码在不同环境下结果不同,可能是因为两个环境下使用不同的解析器造成的.例如这个环境中安装了lxml,而另一个环境中只有html5lib, 解析器之间的区别 中说明了原因.修复方法是在 BeautifulSoup 的构造方法中中指定解析器
  • -
  • 因为HTML标签是 大小写敏感 的,所以3种解析器再出来文档时都将tag和属性转换成小写.例如文档中的 <TAG></TAG> 会被转换为 <tag></tag> .如果想要保留tag的大写的话,那么应该将文档 解析成XML .
  • -
-
-
-

杂项错误

-
    -
  • UnicodeEncodeError: 'charmap' codec can't encode character u'\xfoo' in position bar (或其它类型的 UnicodeEncodeError )的错误,主要是两方面的错误(都不是Beautiful Soup的原因),第一种是正在使用的终端(console)无法显示部分Unicode,参考 Python wiki ,第二种是向文件写入时,被写入文件不支持部分Unicode,这时只要用 u.encode("utf8") 方法将编码转换为UTF-8.
  • -
  • KeyError: [attr] 因为调用 tag['attr'] 方法而引起,因为这个tag没有定义该属性.出错最多的是 KeyError: 'href'KeyError: 'class' .如果不确定某个属性是否存在时,用 tag.get('attr') 方法去获取它,跟获取Python字典的key一样
  • -
  • AttributeError: 'ResultSet' object has no attribute 'foo' 错误通常是因为把 find_all() 的返回结果当作一个tag或文本节点使用,实际上返回结果是一个列表或 ResultSet 对象的字符串,需要对结果进行循环才能得到每个节点的 .foo 属性.或者使用 find() 方法仅获取到一个节点
  • -
  • AttributeError: 'NoneType' object has no attribute 'foo' 这个错误通常是在调用了 find() 方法后直节点取某个属性 .foo 但是 find() 方法并没有找到任何结果,所以它的返回值是 None .需要找出为什么 find() 的返回值是 None .
  • -
-
-
-

如何提高效率

-

Beautiful Soup对文档的解析速度不会比它所依赖的解析器更快,如果对计算时间要求很高或者计算机的时间比程序员的时间更值钱,那么就应该直接使用 lxml .

-

换句话说,还有提高Beautiful Soup效率的办法,使用lxml作为解析器.Beautiful Soup用lxml做解析器比用html5lib或Python内置解析器速度快很多.

-

安装 cchardet 后文档的解码的编码检测会速度更快

-

解析部分文档 不会节省多少解析时间,但是会节省很多内存,并且搜索时也会变得更快.

-
-
-
-

Beautiful Soup 3

-

Beautiful Soup 3是上一个发布版本,目前已经停止维护.Beautiful Soup 3库目前已经被几个主要的linux平台添加到源里:

-

$ apt-get install Python-beautifulsoup

-

在PyPi中分发的包名字是 BeautifulSoup :

-

$ easy_install BeautifulSoup

-

$ pip install BeautifulSoup

-

或通过 Beautiful Soup 3.2.0源码包 安装

-

Beautiful Soup 3的在线文档查看 这里 ,当然还有 中文版 ,然后再读本片文档,来对比Beautiful Soup 4中有什新变化.

-
-

迁移到BS4

-

只要一个小变动就能让大部分的Beautiful Soup 3代码使用Beautiful Soup 4的库和方法—-修改 BeautifulSoup 对象的引入方式:

-
from BeautifulSoup import BeautifulSoup
-
-
-

修改为:

-
from bs4 import BeautifulSoup
-
-
-
    -
  • 如果代码抛出 ImportError 异常“No module named BeautifulSoup”,原因可能是尝试执行Beautiful Soup 3,但环境中只安装了Beautiful Soup 4库
  • -
  • 如果代码跑出 ImportError 异常“No module named bs4”,原因可能是尝试运行Beautiful Soup 4的代码,但环境中只安装了Beautiful Soup 3.
  • -
-

虽然BS4兼容绝大部分BS3的功能,但BS3中的大部分方法已经不推荐使用了,就方法按照 PEP8标准 重新定义了方法名.很多方法都重新定义了方法名,但只有少数几个方法没有向下兼容.

-

上述内容就是BS3迁移到BS4的注意事项

-
-

需要的解析器

-

Beautiful Soup 3曾使用Python的 SGMLParser 解析器,这个模块在Python3中已经被移除了.Beautiful Soup 4默认使用系统的 html.parser ,也可以使用lxml或html5lib扩展库代替.查看 安装解析器 章节

-

因为 html.parser 解析器与 SGMLParser 解析器不同,它们在处理格式不正确的文档时也会产生不同结果.通常 html.parser 解析器会抛出异常.所以推荐安装扩展库作为解析器.有时 html.parser 解析出的文档树结构与 SGMLParser 的不同.如果发生这种情况,那么需要升级BS3来处理新的文档树.

-
-
-

方法名的变化

-
    -
  • renderContents -> encode_contents
  • -
  • replaceWith -> replace_with
  • -
  • replaceWithChildren -> unwrap
  • -
  • findAll -> find_all
  • -
  • findAllNext -> find_all_next
  • -
  • findAllPrevious -> find_all_previous
  • -
  • findNext -> find_next
  • -
  • findNextSibling -> find_next_sibling
  • -
  • findNextSiblings -> find_next_siblings
  • -
  • findParent -> find_parent
  • -
  • findParents -> find_parents
  • -
  • findPrevious -> find_previous
  • -
  • findPreviousSibling -> find_previous_sibling
  • -
  • findPreviousSiblings -> find_previous_siblings
  • -
  • nextSibling -> next_sibling
  • -
  • previousSibling -> previous_sibling
  • -
-

Beautiful Soup构造方法的参数部分也有名字变化:

-
    -
  • BeautifulSoup(parseOnlyThese=...) -> BeautifulSoup(parse_only=...)
  • -
  • BeautifulSoup(fromEncoding=...) -> BeautifulSoup(from_encoding=...)
  • -
-

为了适配Python3,修改了一个方法名:

-
    -
  • Tag.has_key() -> Tag.has_attr()
  • -
-

修改了一个属性名,让它看起来更专业点:

-
    -
  • Tag.isSelfClosing -> Tag.is_empty_element
  • -
-

修改了下面3个属性的名字,以免雨Python保留字冲突.这些变动不是向下兼容的,如果在BS3中使用了这些属性,那么在BS4中这些代码无法执行.

-
    -
  • UnicodeDammit.Unicode -> UnicodeDammit.Unicode_markup``
  • -
  • Tag.next -> Tag.next_element
  • -
  • Tag.previous -> Tag.previous_element
  • -
-
-
-

生成器

-

将下列生成器按照PEP8标准重新命名,并转换成对象的属性:

-
    -
  • childGenerator() -> children
  • -
  • nextGenerator() -> next_elements
  • -
  • nextSiblingGenerator() -> next_siblings
  • -
  • previousGenerator() -> previous_elements
  • -
  • previousSiblingGenerator() -> previous_siblings
  • -
  • recursiveChildGenerator() -> descendants
  • -
  • parentGenerator() -> parents
  • -
-

所以迁移到BS4版本时要替换这些代码:

-
for parent in tag.parentGenerator():
-    ...
-
-
-

替换为:

-
for parent in tag.parents:
-    ...
-
-
-

(两种调用方法现在都能使用)

-

BS3中有的生成器循环结束后会返回 None 然后结束.这是个bug.新版生成器不再返回 None .

-

BS4中增加了2个新的生成器, .strings 和 stripped_strings . .strings 生成器返回NavigableString对象, .stripped_strings 方法返回去除前后空白的Python的string对象.

-
-
-

XML

-

BS4中移除了解析XML的 BeautifulStoneSoup 类.如果要解析一段XML文档,使用 BeautifulSoup 构造方法并在第二个参数设置为“xml”.同时 BeautifulSoup 构造方法也不再识别 isHTML 参数.

-

Beautiful Soup处理XML空标签的方法升级了.旧版本中解析XML时必须指明哪个标签是空标签. 构造方法的 selfClosingTags 参数已经不再使用.新版Beautiful Soup将所有空标签解析为空元素,如果向空元素中添加子节点,那么这个元素就不再是空元素了.

-
-
-

实体

-

HTML或XML实体都会被解析成Unicode字符,Beautiful Soup 3版本中有很多处理实体的方法,在新版中都被移除了. BeautifulSoup 构造方法也不再接受 smartQuotesToconvertEntities 参数. 编码自动检测 方法依然有 smart_quotes_to 参数,但是默认会将引号转换成Unicode.内容配置项 HTML_ENTITIES , XML_ENTITIESXHTML_ENTITIES 在新版中被移除.因为它们代表的特性已经不再被支持.

-

如果在输出文档时想把Unicode字符转换成HTML实体,而不是输出成UTF-8编码,那就需要用到 输出格式 的方法.

-
-
-

迁移杂项

-

Tag.string 属性现在是一个递归操作.如果A标签只包含了一个B标签,那么A标签的.string属性值与B标签的.string属性值相同.

-

多值属性 比如 class 属性包含一个他们的值的列表,而不是一个字符串.这可能会影响到如何按照CSS类名哦搜索tag.

-

如果使用 find* 方法时同时传入了 text 参数name 参数 .Beautiful Soup会搜索指定name的tag,并且这个tag的 Tag.string 属性包含text参数的内容.结果中不会包含字符串本身.旧版本中Beautiful Soup会忽略掉tag参数,只搜索text参数.

-

BeautifulSoup 构造方法不再支持 markupMassage 参数.现在由解析器负责文档的解析正确性.

-

很少被用到的几个解析器方法在新版中被移除,比如 ICantBelieveItsBeautifulSoupBeautifulSOAP .现在由解析器完全负责如何解释模糊不清的文档标记.

-

prettify() 方法在新版中返回Unicode字符串,不再返回字节流.

-

BeautifulSoup3 文档

- - - - - -
[1]BeautifulSoup的google讨论组不是很活跃,可能是因为库已经比较完善了吧,但是作者还是会很热心的尽量帮你解决问题的.
- - - - - -
[2](1, 2) 文档被解析成树形结构,所以下一步解析过程应该是当前节点的子节点
- - - - - -
[3]过滤器只能作为搜索文档的参数,或者说应该叫参数类型更为贴切,原文中用了 filter 因此翻译为过滤器
- - - - - -
[4]元素参数,HTML文档中的一个tag节点,不能是文本节点
- - - - - -
[5](1, 2, 3, 4, 5) 采用先序遍历方式
- - - - - -
[6](1, 2) CSS选择器是一种单独的文档搜索语法, 参考 http://www.w3school.com.cn/css/css_selector_type.asp
- - - - - -
[7]原文写的是 html5lib, 译者觉得这是愿文档的一个笔误
- - - - - -
[8]wrap含有包装,打包的意思,但是这里的包装不是在外部包装而是将当前tag的内部内容包装在一个tag里.包装原来内容的新tag依然在执行 wrap() 方法的tag内
- - - - - -
[9]文档中特殊编码字符被替换成特殊字符(通常是�)的过程是Beautful Soup自动实现的,如果想要多种编码格式的文档被完全转换正确,那么,只好,预先手动处理,统一编码格式
- - - - - -
[10](1, 2) 智能引号,常出现在microsoft的word软件中,即在某一段落中按引号出现的顺序每个引号都被自动转换为左引号,或右引号.
-
-
-
- - -
-
-
-
-
-

Table Of Contents

- - -

This Page

- - - -
-
-
-
- - - - \ No newline at end of file diff --git a/doc/source/README b/doc/source/README new file mode 100644 index 0000000..6fbab84 --- /dev/null +++ b/doc/source/README @@ -0,0 +1,23 @@ +Translation credits +################### + +I keep a copy of all translations in this repository so that it's easy +to host translations on the Beautiful Soup website. These are +generally not the canonical versions of the translations, though. + +doc.html/index.jp.html is a copy of the 2013 Japanese translation hosted at +http://kondou.com/BS4/. I don't know who to credit for the +translation. + +doc.html/index.kr.html is a copy of the 2012 Korean translation formerly hosted +at http://coreapython.hosting.paran.com/etc/beautifulsoup4.html. I +retrieved this copy from the Wayback Machine. I'm not sure who wrote +the translation but I believe the credit goes to "Johnsonj". + +doc.ptbr/source/index.rst is a 2019 Brazilian Portuguese translation by Cezar +Peixeiro. The version in this repository has been modified from +https://github.com/czrpxr/BeautifulSoup4-ptbr-translation. + +doc.zh/source/index.rst is a 2018 Chinese translation by Deron +Wang. The version in this repository has been copied from +https://github.com/DeronW/beautifulsoup. diff --git a/doc/source/index.ptbr.rst b/doc/source/index.ptbr.rst deleted file mode 100644 index f596d44..0000000 --- a/doc/source/index.ptbr.rst +++ /dev/null @@ -1,3261 +0,0 @@ -Documentação Beautiful Soup -============================ - -.. image:: 6.1.jpg - :align: right - :alt: "O Lacaio-Peixe começou tirando debaixo do braço uma grande carta, quase tão grande quanto ele mesmo." - - -`Beautiful Soup `_ é uma biblioteca -Python de extração de dados de arquivos HTML e XML. Ela funciona com o seu interpretador (parser) favorito -a fim de prover maneiras mais intuitivas de navegar, buscar e modificar uma árvore de análise (parse tree). -Ela geralmente economiza horas ou dias de trabalho de programadores ao redor do mundo. - -Estas instruções ilustram as principais funcionalidades do Beautiful Soup 4 -com exemplos. Mostro para o que a biblioteca é indicada, como funciona, -como se usa e como fazer aquilo que você quer e o que fazer quando ela frustra suas -expectativas. - -Os exemplos nesta documentação devem funcionar da mesma maneira em Python 2.7 e Python 3.2. - -`Você pode estar procurando pela documentação do Beautiful Soup 3 -`_. -Se está, informo que o Beautiful Soup 3 não está mais sendo desenvolvido, -e que o Beautiful Soup 4 é o recomendado para todos os novos projetos. -Se você quiser saber as diferenças entre as versões 3 e 4, veja `Portabilidade de código para BS4`_. - -Esta documentação foi traduzida para outros idiomas pelos usuários do Beautiful Soup: - -* `这篇文档当然还有中文版. `_ -* このページは日本語で利用できます(`外部リンク `_) -* 이 문서는 한국어 번역도 가능합니다. (`외부 링크 `_) -* Este documento também está disponível em Português do Brasil - -Como conseguir ajuda: ---------------------- - -Se você tem perguntas sobre o Beautiful Soup ou está com dificuldades, -`envie uma mensagem para nosso grupo de discussão -`_. Se o seu -problema envolve a interpretação de um documento HTML, não esqueça de mencionar -:ref:`o que a função diagnose() diz ` sobre seu documento. - -Início Rápido -============= - -Este é o HTML que usarei como exemplo ao longo deste documento -É um trecho de "Alice no País das Maravilhas":: - - html_doc = """ - The Dormouse's story - -

The Dormouse's story

- -

Once upon a time there were three little sisters; and their names were - Elsie, - Lacie and - Tillie; - and they lived at the bottom of a well.

- -

...

- """ - -Executando o arquivo "three sisters" através do Beautiful Soup, ele nos -retorna um objeto ``BeautifulSoup``, que apresenta o documento como uma estrutura -de dados aninhada:: - - from bs4 import BeautifulSoup - soup = BeautifulSoup(html_doc, 'html.parser') - - print(soup.prettify()) - # - # - # - # The Dormouse's story - # - # - # - #

- # - # The Dormouse's story - # - #

- #

- # Once upon a time there were three little sisters; and their names were - # - # Elsie - # - # , - # - # Lacie - # - # and - # - # Tillie - # - # ; and they lived at the bottom of a well. - #

- #

- # ... - #

- # - # - -Abaixo verificamos algumas maneiras simples de navegar na estrutura:: - - soup.title - # The Dormouse's story - - soup.title.name - # u'title' - - soup.title.string - # u'The Dormouse's story' - - soup.title.parent.name - # u'head' - - soup.p - #

The Dormouse's story

- - soup.p['class'] - # u'title' - - soup.a - # Elsie - - soup.find_all('a') - # [Elsie, - # Lacie, - # Tillie] - - soup.find(id="link3") - # Tillie - -Uma tarefa comum é extratir todas as URLs encontradas nas tags de uma página:: - - for link in soup.find_all('a'): - print(link.get('href')) - # http://example.com/elsie - # http://example.com/lacie - # http://example.com/tillie - -Outra tarefa comum é extrair todo o texto de uma página:: - - print(soup.get_text()) - # The Dormouse's story - # - # The Dormouse's story - # - # Once upon a time there were three little sisters; and their names were - # Elsie, - # Lacie and - # Tillie; - # and they lived at the bottom of a well. - # - # ... - -Isso se parece com o que você precisa? Então vá em frente! - -Instalando o Beautiful Soup -=========================== - -Se você está usando uma versão recente das distribuições Linux Debian ou Ubuntu, -você pode instalar o Beautiful Soup facilmente utilizando o gerenciador de pacotes - -:kbd:`$ apt-get install python-bs4` (for Python 2) - -:kbd:`$ apt-get install python3-bs4` (for Python 3) - -O Beautiful Soup 4 também está publicado no PyPi. Portanto, se -você não conseguir instalá-lo através de seu gerenciador de pacotes, você -pode fazer isso com ``easy_install`` ou ``pip``. O nome do pacote é ``beautifulsoup4``, -e o mesmo pacote é válido tanto para Python 2 quanto Python 3. Tenha certeza de utilizar -a versão correta de ``pip`` ou ``easy_install`` para sua versão do Python (estarão -nomeados como ``pip3`` ou ``easy_install3`` ,respectivamente, se você estiver usando Python 3). - - -:kbd:`$ easy_install beautifulsoup4` - -:kbd:`$ pip install beautifulsoup4` - -(O pacote ``BeautifulSoup`` provavelmente `não` é o que você quer. Esta -é a versão anterior, `Beautiful Soup 3`_. Muitos softwares utilizam -BS3, por isso ele ainda está disponível, mas se você está criando algo novo, -você deve instalar o ``beautifulsoup4``.) - -Se você não possui o ``easy_install`` ou ``pip`` instalados, você pode fazer -o download através do tarball do arquivo fonte do Beautiful Soup 4 -`_ e -instalar através do ``setup.py``. - -:kbd:`$ python setup.py install` - -Se tudo isso falhar, a licença do Beautiful Soup lhe permite empacotar -toda a biblioteca em sua aplicação. Você pode fazer o download do arquivo -tarball, copiar o diretório ``bs4`` do código-fonte para sua aplicação e -utilizar o Beautiful Soup sem nenhum processo de instalação. - -Eu utilizo Python 2.7 e Python 3.2 para desenvolver o Beautiful Soup, -mas ele também funcionará com outras versões recentes. - -Problemas após a instalação ---------------------------- - -O Beautiful Soup é empacotado em Python 2. Quando você o instala utilizando -Python 3 ele é automaticamente convertido para esta versão. Se você não instalar o pacote, o -código não será convertido. Também foi relatado versões erradas sendo instaladas em -máquinas Windows. - -Se você receber um ``ImportError`` "No module named HTMLParser", seu problema -é que você está utilizando o formato de código Python 2 sob Python 3. - -Se você receber um ``ImportError`` "No module named html.parser", seu problema -é que você está utilizando o formato de código Python 3 sob Python 2. - -Em ambos os casos, sua melhor opção é remover completamente a -instalação do Beautiful Soup do seu sistema (incluindo qualquer diretório -criado quando o tarball foi descompactado) e realizar a instalação novamente. - -Se você receber um ``SyntaxError`` "Invalid syntax" na linha -``ROOT_TAG_NAME = u'[document]'``, você terá que converter o Python 2 -em Python 3. Você pode fazer isso instalando o pacote: - -:kbd:`$ python3 setup.py install` - -ou manualmente executando o script de conversão ``2to3`` no -diretório ``bs4``: - -:kbd:`$ 2to3-3.2 -w bs4` - -.. _parser-installation: - - -Instalando um interpretador (parser) ------------------------------------- - - -O Beautiful Soup não só suporta o parser HTML incluído na biblioteca -padrão do Python como também inúmeros parsers de terceiros. -Um deles é o `parser lxml `_. Dependendo de sua configuração, -você podera instalar o lxml com algum dos seguintes comandos: - -:kbd:`$ apt-get install python-lxml` - -:kbd:`$ easy_install lxml` - -:kbd:`$ pip install lxml` - -Outra alternativa é o parser `html5lib -`_ do Python puro, o qual analisa o HTML -da mesma maneira que o navegador o faz. Dependendo de sua configuração, -você podera instalar o html5lib com algum dos seguintes comandos: - -:kbd:`$ apt-get install python-html5lib` - -:kbd:`$ easy_install html5lib` - -:kbd:`$ pip install html5lib` - -Esta tabela resume as vantagens e desvantagens de cada parser:- - -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ -| Parser | Uso Padrão | Vantagens | Desvantagens | -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ -| html.parser (puro) | ``BeautifulSoup(markup, "html.parser")`` | * Baterias inclusas | * Não tão rápido quanto | -| | | * Velocidade Decente | lxml, menos leniente | -| | | * Leniente (Python 2.7.3 | que html5lib. | -| | | e 3.2.) | | -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ -| HTML (lxml) | ``BeautifulSoup(markup, "lxml")`` | * Muito rápido | * Dependencia externa de | -| | | * Leniente | C | -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ -| XML (lxml) | ``BeautifulSoup(markup, "lxml-xml")`` | * Muito rápido | * Dependência externa de | -| | ``BeautifulSoup(markup, "xml")`` | * O único parser XML atualmente| C | -| | | suportado | | -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ -| html5lib | ``BeautifulSoup(markup, "html5lib")`` | * Extremamente leniente | * Muito lento | -| | | * Analisa as páginas da mesma | * Dependência externa de | -| | | maneira que o navegador o faz| Python | -| | | * Cria HTML5 válidos | | -+----------------------+--------------------------------------------+--------------------------------+--------------------------+ - -Se for possível recomendo que você instale e utilize o lxml pelo desempenho. -Se você está utilizando o Python 2 anterior a 2.7.3 ou uma versão do Python 3 -anterior a 3.2.2, é `essencial` que você instale o lxml ou o html5lib. O parser -HTML nativo do Python não é muito bom para versões mais antigas. - -Note que se um documento é inválido, diferentes parsers irão gerar -diferentes árvores BeautifulSoup para isso. Veja :ref:`Diferenças entre os interpretadores (parsers)` -para detalhes. - - -Criando a "Sopa" -================ - -Para analisar um documento, passe-o como argumento dentro de um construtor ``BeautifulSoup``. -Você pode passar este argumento como uma string ou manipulador da função open():: - - from bs4 import BeautifulSoup - - with open("index.html") as fp: - soup = BeautifulSoup(fp) - - soup = BeautifulSoup("data") - -Primeiro, o documento é convertido para Unicode e as entidades HTML -são convertidas para caracteres Unicode:: - - BeautifulSoup("Sacré bleu!") - Sacré bleu! - -O Beautiful Soup então interpreta o documento usando o melhor parser disponível. -Ele irá utilizar um parser HTML ao menos que você indique a ele que utilize um -parser XML.(Veja `Interpretando XML`_.) - -Tipos de objetos -================ - -O Beautiful Soup transforma um documento HTML complexo em uma complexa árvore de objetos Python. -Mas você terá apenas que lidar com quatro `tipos` de objetos: ``Tag``, ``NavigableString``, ``BeautifulSoup``, -e ``Comment``. - -.. _Tag: - -``Tag`` -------- - -Um objeto ``Tag`` corresponde a uma tag XML ou HTML do documento original:: - - soup = BeautifulSoup('Extremely bold') - tag = soup.b - type(tag) - # - -As tags possuem muitos atributos e métodos que eu falarei mais sobre em -`Navegando pela árvore`_ e `Buscando na árvore`_. Por agora, as características -mais importantes da tag são seu nome e atributos. - -Nome -^^^^ - -Toda tag possui um nome, acessível através de ``.name``:: - - tag.name - # u'b' - -Se você mudar o nome de uma tag, a alteração será refletida em qualquer HTML gerado pelo -Beautiful Soup:: - - tag.name = "blockquote" - tag - #
Extremely bold
- -Atributos -^^^^^^^^^^ -Uma tag pode ter inúmeros atributos. A tag ```` -possui um atributo "id" que possui o valor "boldest". Você pode -acessar um atributo de uma tag tratando-a como um dicionário:: - - tag['id'] - # u'boldest' - -Você pode acessar este dicionário diretamente através de ``.attrs``:: - - tag.attrs - # {u'id': 'boldest'} - -Você pode adicionar, remover ou modificar os atributos de uma tag. Novamente, isso pode -ser feito tratando a tag como um dicionário:: - - tag['id'] = 'verybold' - tag['another-attribute'] = 1 - tag - # - - del tag['id'] - del tag['another-attribute'] - tag - # - - tag['id'] - # KeyError: 'id' - print(tag.get('id')) - # None - -.. _multivalue: - -Atributos com múltiplos valores -&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& - -O HTML 4 define alguns atributos que podem ter múltiplos valores. O HTML 5 -removeu alguns deles, mas definiu alguns novos. O atributo mais comum -que pode receber múltiplos valores é o ``class`` (ou seja, a tag pode ter mais de uma classe CSS). -Outros são ``rel``, ``rev``, ``accept-charset``, ``headers``, e ``accesskey``. -O Beautiful Soup apresenta o(s) valor(es) de um atributo deste tipo como uma lista:: - - css_soup = BeautifulSoup('

') - css_soup.p['class'] - # ["body"] - - css_soup = BeautifulSoup('

') - css_soup.p['class'] - # ["body", "strikeout"] - -Se um atributo possui mais de um valor, mas não é um atributo -que aceita múltiplos valores conforme definido por qualquer versão do -padrão HTML, o Beautiful Soup retornará como um valor único:: - - id_soup = BeautifulSoup('

') - id_soup.p['id'] - # 'my id' - -Quando a tag é transformada novamente em string, os valores do atributo múltiplo -são consolidados:: - - rel_soup = BeautifulSoup('

Back to the homepage

') - rel_soup.a['rel'] - # ['index'] - rel_soup.a['rel'] = ['index', 'contents'] - print(rel_soup.p) - #

Back to the homepage

- -Você pode desabilitar esta opção passando ``multi_valued_attributes=None`` como argumento -dentro do construtor ``BeautifulSoup`` :: - - no_list_soup = BeautifulSoup('

', 'html', multi_valued_attributes=None) - no_list_soup.p['class'] - # u'body strikeout' - -Você pode utilizar ```get_attribute_list`` para retornar um valor no formato de lista, seja um atributo de -múltiplos valores ou não:: - - id_soup.p.get_attribute_list('id') - # ["my id"] - -Se você analisar um documento como XML, nenhum atributo será tratado como de múltiplos valores:: - - xml_soup = BeautifulSoup('

', 'xml') - xml_soup.p['class'] - # u'body strikeout' - -Novamente, você pode configurar isto usando o argumento ``multi_valued_attributes``:: - - class_is_multi= { '*' : 'class'} - xml_soup = BeautifulSoup('

', 'xml', multi_valued_attributes=class_is_multi) - xml_soup.p['class'] - # [u'body', u'strikeout'] - -Você provavelmente não precisará fazer isso, mas se fizer, use os padrões como guia. -Eles implementam as regras descritas na especificação do HTML:: - - from bs4.builder import builder_registry - builder_registry.lookup('html').DEFAULT_CDATA_LIST_ATTRIBUTES - - -``NavigableString`` -------------------- - -Uma string corresponde a um texto dentro de uma tag. -O Beautiful Soup usa a classe ``NavigableString`` para armazenar este texto:: - - tag.string - # u'Extremely bold' - type(tag.string) - # - -Uma ``NavigableString`` é como uma string Unicode do Python, exceto -que ela também suporta algumas características descritas em `Navegando pela árvore`_ -e `Buscando na árvore`_. Você pode converter um -``NavigableString`` em uma string Unicode utilizando ``unicode()``:: - - unicode_string = unicode(tag.string) - unicode_string - # u'Extremely bold' - type(unicode_string) - # - -Você não pode editar uma string "in place", mas você pode substituir -uma string por outra usando :ref:`replace_with()`:: - - tag.string.replace_with("No longer bold") - tag - #
No longer bold
- -``NavigableString`` suporta a maior parte das características descritas em -`Navegando pela árvore`_ e `Buscando na árvore`_, mas não todas elas. -Em particular, desde que uma string não pode conter de tudo (da maneira que -uma tag pode conter uma string ou outra tag), as strings não suportam os -atributos ``.contents`` ou ``.string`` ou o método ``find()``. - -Se você quer utilizar uma ``NavigableString`` fora do Beautiful Soup, -você deve chamar o ``unicode()`` para transformá-la em uma string Unicode Python -padrão. Se você não fizer isso, sua string irá carregar uma referência de toda sua -árvore Beautiful Soup, mesmo que você já não esteja mais usando ela, o que é um grande -desperdício de memória. - -``BeautifulSoup`` ------------------ - -O objeto ``BeautifulSoup`` em si representa o documento como um todo. -Para maioria dos propósitos, você pode tratá-lo como um objeto :ref:`Tag`. -Isso significa que irá suportar a maioria dos métodos descritos em -`Navegando pela árvore`_ e `Buscando na árvore`_. - -Sabendo que o objeto ``BeautifulSoup`` não corresponde a uma tag -HTML ou XML propriamente dita, ele não tem nome e nem atributos. Mas em alguns -casos é útil observar seu ``.name``; então, foi dado o especial -``.name`` "[document]":: - - soup.name - # u'[document]' - -Comentários e outras strings especiais --------------------------------------- - -``Tag``, ``NavigableString``, e ``BeautifulSoup`` abrangem quase -tudo o que você encontrará em um arquivo HTML ou XML, mas há alguns -pontos faltando. O único deles que você provavelmente precisará se preocupar -é o comentário:: - - markup = "" - soup = BeautifulSoup(markup) - comment = soup.b.string - type(comment) - # - -O objeto ``Comment`` é apenas um tipo especial de ``NavigableString``:: - - comment - # u'Hey, buddy. Want to buy a used parser' - -Mas quando aparece como parte de um documento HTML, um ``Comment`` é -exibido com uma formatação especial:: - - print(soup.b.prettify()) - # - # - # - -O Beautiful Soup define classes para qualquer outra coisa que possa -aparecer em um documento XML: ``CData``, ``ProcessingInstruction``, -``Declaration`` e ``Doctype``. Assim como ``Comment``, estas classes -são subclasses de ``NavigableString`` que adicionam algo a string. -Aqui está um exemplo que substitui o comentário por um bloco CDATA:: - - from bs4 import CData - cdata = CData("A CDATA block") - comment.replace_with(cdata) - - print(soup.b.prettify()) - # - # - # - - -Navegando pela árvore -===================== - -Aqui está o documento HTML "Three sisters" novamente:: - - html_doc = """ - The Dormouse's story - -

The Dormouse's story

- -

Once upon a time there were three little sisters; and their names were - Elsie, - Lacie and - Tillie; - and they lived at the bottom of a well.

- -

...

- """ - - from bs4 import BeautifulSoup - soup = BeautifulSoup(html_doc, 'html.parser') - -Eu usarei este documento como exemplo para mostrar como navegar -de uma parte para outra do documento. - -Descendo na Árvore ------------------- -As tags podem conter strings e outras tags. Estes elementos são as tags -`filhas` (children). O Beautiful Soup oferece diferentes atributos para -navegar e iterar sobre as tags filhas. - -Note que as strings Beautiful Soup não suportam qualquer destes atributos, -porque uma string não pode ter filhos. - -Navegar usando os nomes das tags -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -A maneira mais simples de navegar pela árvore é utilizar -o nome da tag que você quer. Se você quer a tag , -simplesmente use ``soup.head``:: - - soup.head - # The Dormouse's story - - soup.title - # The Dormouse's story - -Você pode usar este truque de novo, e de novo, para focar em certa parte da -árvore de análise. Este código retorna a primeira tag abaixo da tag :: - - soup.body.b - # The Dormouse's story - -Utilizando o nome da tag como atributo irá lhe retornar apenas a `primeira` -tag com aquele nome:: - - soup.a - # Elsie - -Se você precisar retornar `todas` as tags , ou algo mais complicado -que a primeira tag com um certo nome, você precisará utilizar um dos -métodos descritos em `Buscando na árvore`_, como `find_all()`:: - - soup.find_all('a') - # [Elsie, - # Lacie, - # Tillie] - -``.contents`` e ``.children`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -As tags filhas de uma outra tag estão disponíveis em uma lista chamada por ``.contents``:: - - head_tag = soup.head - head_tag - # The Dormouse's story - - head_tag.contents - [The Dormouse's story] - - title_tag = head_tag.contents[0] - title_tag - # The Dormouse's story - title_tag.contents - # [u'The Dormouse's story'] - -O objeto ``BeautifulSoup`` em si possui filhos. Neste caso, a tag - é a filha do objeto ``BeautifulSoup``.:: - - len(soup.contents) - # 1 - soup.contents[0].name - # u'html' - -Uma string não possui o atributo ``.contents``, porque ela não pode conter -nada:: - - text = title_tag.contents[0] - text.contents - # AttributeError: 'NavigableString' object has no attribute 'contents' - -Ao invés de retorná-las como uma lista, você pode iterar sobre as -tag's filhas usando o gerador ``.children``:: - - for child in title_tag.children: - print(child) - # The Dormouse's story - -``.descendants`` -^^^^^^^^^^^^^^^^ - -Os atributos ``.contents`` e ``.children`` somente consideram tags que -são `filhas diretas`. Por instância, a tag tem apenas uma tag filha direta, -a tag :: - - head_tag.contents - # [<title>The Dormouse's story] - -Mas a tag em si possui uma filha: a string "The Dormouse's story". -Existe uma percepção de que esta string também é filha da tag <head>. -O atributo ``.descendants`` permite que você itere sobre `todas` -as tags filhas, recursivamente: suas filhas diretas, as filhas de suas filhas, e assim por diante:: - - for child in head_tag.descendants: - print(child) - # <title>The Dormouse's story - # The Dormouse's story - -A tag possui apenas uma filha, mas também possui dois `descentendes`: -a tag e a filha da tag <title>. O objeto ``BeautifulSoup`` possui apenas -uma filha direta (a tag <html>), mas ele possui vários descendentes:: - - len(list(soup.children)) - # 1 - len(list(soup.descendants)) - # 25 - -.. _.string: - -``.string`` -^^^^^^^^^^^ - -Se uma tag possui apenas uma filha, e esta filha é uma ``NavigableString``, -esta filha pode ser disponibilizada através de ``.string``:: - - title_tag.string - # u'The Dormouse's story' - -Se a filha única de uma tag é outra tag e esta tag possui uma -``.string``, então considera-se que a tag mãe tenha a mesma -``.string`` como sua filha:: - - head_tag.contents - # [<title>The Dormouse's story] - - head_tag.string - # u'The Dormouse's story' - -Se uma tag contém mais de uma coisa, então não fica claro a que -``.string`` deve se referir, portanto ``.string`` será definida como -``None``:: - - print(soup.html.string) - # None - -.. _string-generators: - -``.strings`` e ``stripped_strings`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Se existe mais de alguma coisa dentro da tag, você pode continuar -olhando apenas as strings. Use o gerador ``.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' - -Estas strings tendem a ter muitos espaços em branco, os quais você -pode remover utilizando o gerador ``.stripped_strings`` como alternativa:: - - 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'...' - -Aqui, strings formadas inteiramente por espaços em branco serão ignoradas, -e espaços em branco no início e no fim das strings serão removidos. - -Subindo na Árvore ------------------ - -Continuando a analogia da árvore como "família", toda tag e toda string possuem -`tags mães (parents)`: a tag que as contém. - -.. _.parent: - -``.parent`` -^^^^^^^^^^^ - -Você pode acessar o elemento mãe com o atributo ``.parent``. No -exemplo "three sisters", a tag é mãe da tag :: - - title_tag = soup.title - title_tag - # <title>The Dormouse's story - title_tag.parent - # The Dormouse's story - -A string de title tem uma mãe: a tag que a contém:: - - title_tag.string.parent - # <title>The Dormouse's story - -A tag mãe de todo documento () é um objeto ``BeautifulSoup`` em si:: - - html_tag = soup.html - type(html_tag.parent) - # - -E o ``.parent`` de um objeto ``BeautifulSoup`` é definido como None:: - - print(soup.parent) - # None - -.. _.parents: - -``.parents`` -^^^^^^^^^^^^ -Você pode iterar sobre todos os elementos pais com -``.parents``. Este exemplo usa ``.parents`` para viajar de uma tag -profunda no documento, para o elemento mais ao topo da árvore do documento:: - - link = soup.a - link - # Elsie - for parent in link.parents: - if parent is None: - print(parent) - else: - print(parent.name) - # p - # body - # html - # [document] - # None - -Navegando para os lados: ------------------------- - -Considere um simples documento como este:: - - sibling_soup = BeautifulSoup("text1text2") - print(sibling_soup.prettify()) - # - # - # - # - # text1 - # - # - # text2 - # - # - # - # - -A tag e a tag estão no mesmo nível: ambas são filhas diretas -da mesma tag. Nós podemos chamá-las irmãs (`siblings`). -Quando um documento é pretty-printed, irmãs aparecem no mesmo nível de identação. -Você pode utilizar esta relação nos códigos que você escrever. - -``.next_sibling`` e ``.previous_sibling`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Você pode usar ``.next_sibling`` e ``.previous_sibling`` para navegar -entre os elementos da página que estão no mesmo nível da árvore:: - - sibling_soup.b.next_sibling - # text2 - - sibling_soup.c.previous_sibling - # text1 - -A tag possui ``.next_sibling``, mas não ``.previous_sibling``, -porque não há nada antes da tag `no mesmo nível na árvore`. -Pela mesma razão, a tag possui ``.previous_sibling`` -mas não ``.next_sibling``:: - - print(sibling_soup.b.previous_sibling) - # None - print(sibling_soup.c.next_sibling) - # None - -As strings "text1" e "text2" `não` são irmãs, porque elas não tem a mesma tag mãe:: - - sibling_soup.b.string - # u'text1' - - print(sibling_soup.b.string.next_sibling) - # None - -No mundo real, ``.next_sibling`` ou ``.previous_sibling`` de uma tag -geralmente são strings contendo espaços em branco. Voltando ao documento -"three sisters":: - - Elsie - Lacie - Tillie - -Você pode pensar que o ``.next_sibling`` da primeira tag será a segunda tag . -Mas na verdade é uma string: a vírgula e um caracter de nova linha (\n) que separam -a primeira da segunda tag :: - - link = soup.a - link - # Elsie - - link.next_sibling - # u',\n' - -A segunda tag é, na verdade, a ``.next_sibling`` da vírgula:: - - link.next_sibling.next_sibling - # Lacie - -.. _sibling-generators: - -``.next_siblings`` e ``.previous_siblings`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Você pode iterar sobre as tag's filhas com ``.next_siblings`` -ou ``.previous_siblings``:: - - for sibling in soup.a.next_siblings: - print(repr(sibling)) - # u',\n' - # Lacie - # u' and\n' - # Tillie - # u'; and they lived at the bottom of a well.' - # None - - for sibling in soup.find(id="link3").previous_siblings: - print(repr(sibling)) - # ' and\n' - # Lacie - # u',\n' - # Elsie - # u'Once upon a time there were three little sisters; and their names were\n' - # None - -Indo e voltando ----------------- - -Dê uma olhada no início do documento "three sisters":: - - The Dormouse's story -

The Dormouse's story

- -Um parser HTML transforma estas strings em uma série de eventos: "abrir -uma tag ", "abrir uma tag ", "abrir uma tag ", -"adicionar uma string", "fechar uma tag <title>, -"abrir uma tag <p>", e daí por diante. O Beautiful Soup oferece ferramentas -para reconstruir a análise inicial do documento. - -.. _element-generators: - -``.next_element`` e ``.previous_element`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -O atributo ``.next_element`` de uma string ou tag aponta para -qualquer coisa que tenha sido interpretado posteriormente. -Isso deveria ser o mesmo que ``.next_sibling``, mas é -drasticamente diferente. - -Aqui está a tag <a> final no "three sisters". Sua -``.next_sibling`` é uma string: a conclusão da sentença -que foi interrompida pelo início da tag <a>.:: - - last_a_tag = soup.find("a", id="link3") - last_a_tag - # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> - - last_a_tag.next_sibling - # '; and they lived at the bottom of a well.' - -Mas no ``.next_element`` da tag <a>, o que é analisado imediatamente -depois da tag <a> `não` é o resto da sentença: é a palavra "Tillie". - - last_a_tag.next_element - # u'Tillie' - -Isso porque na marcação original, a palavra "Tillie" apareceu -antes do ponto e virgula. O parser encontrou uma tag <a>, então -a palavra "Tillie", então fechando a tag </a>, então o ponto e vírgula e o -resto da sentença. O ponto e vírgula estão no mesmo nível que a tag <a>, -mas a palavra "Tillie" foi encontrada primeiro. - -O atributo ``.previous_element`` é exatamente o oposto de -``.next_element``. Ele aponta para qualquer elemento que -seja analisado antes do respectivo:: - - last_a_tag.previous_element - # u' and\n' - last_a_tag.previous_element.next_element - # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> - -``.next_elements`` e ``.previous_elements`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Você deve ter entendido a idéia agora. Você pode usar estes iteradores -para andar para frente e para atrás no documento quando ele for analisado:: - - for element in last_a_tag.next_elements: - print(repr(element)) - # u'Tillie' - # u';\nand they lived at the bottom of a well.' - # u'\n\n' - # <p class="story">...</p> - # u'...' - # u'\n' - # None - -Buscando na árvore -================== - -O Beautiful Soup define vários métodos para buscar na árvore que está sendo analisada, -mas eles são todos muito similares. Vou usar a maior parte do tempo para explicar os dois mais -populares métodos: ``find()`` e ``find_all()``. Os outros métodos recebem exatamente -os mesmos argumentos, portanto, vou cobrí-los apenas brevemente. - - -Mais uma vez, utilizarei o documento "three sisters" como exemplo:: - - html_doc = """ - <html><head><title>The Dormouse's story - -

The Dormouse's story

- -

Once upon a time there were three little sisters; and their names were - Elsie, - Lacie and - Tillie; - and they lived at the bottom of a well.

- -

...

- """ - - from bs4 import BeautifulSoup - soup = BeautifulSoup(html_doc, 'html.parser') - -Utilizando em um filtro um argumento como ``find_all()``, você pode -"dar um zoom" nas partes do documento que você está interessado. - -Tipos de filtros ----------------- - -Antes de entrar em detalhes sobre o ``find_all()`` e métodos similares, -quero mostrar exemplos de diferentes filtros que você pode passar dentro -destes métodos. Estes filtros aparecerão de novo e de novo por toda API -de pesquisa. Você pode usá-los para realizar filtros baseados nos nomes das tags, -nos seus atributos, no texto de uma strings ou em alguma combinação entre eles. - -.. _uma string: - -Uma string -^^^^^^^^^^ - -O filtro mais simples é uma string. Passando uma string para um método de pesquisa, -o Beautiful Soup irá buscar uma correspondência a esta exata string. O seguinte código -encontrará todas as tags no documento:: - - soup.find_all('b') - # [The Dormouse's story] - -Se você passar uma byte string, o Beautiful Soup assumirá que a string -esta codificada como UTF-8. Você pode evitar isso passando ao invés disso -uma string Unicode. - -.. _uma expressão regular: - -Uma expressão regular (regex) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Se você passar um objeto `regex`, o Beautiful Soup irá -realizar um filtro com ela utilizando seu método ``search()``. -O código seguinte buscará todas as tags as quais os nomes comecem com -a letra "b"; neste caso, a tag e a tag :: - - import re - for tag in soup.find_all(re.compile("^b")): - print(tag.name) - # body - # b - -Este código buscará todas as tags cujo nome contenha a letra "t":: - - for tag in soup.find_all(re.compile("t")): - print(tag.name) - # html - # title - -.. _uma lista: - -Uma lista -^^^^^^^^^ - -Se você passar uma lista, o Beautiful Soup irá buscar -uma correspondência com qualquer item dessuma lista. -O código seguinte buscará todas as tags e todas -as tags :: - - soup.find_all(["a", "b"]) - # [The Dormouse's story, - # Elsie, - # Lacie, - # Tillie] - -.. _the value True: - -``True`` -^^^^^^^^ - -O valor ``True`` irá corresponder com tudo. -O código abaixo encontrará ``todas`` as tags do documento, -mas nenhuma das strings:: - - for tag in soup.find_all(True): - print(tag.name) - # html - # head - # title - # body - # p - # b - # p - # a - # a - # a - # p - -.. _a function: - -Uma function -^^^^^^^^^^^^ - -Se nenhuma das opções anteriores funcionar para você, defina uma -função que pegará um elemento como seu único argumento. A função -deverá retornar ``True`` se o argumento corresponder e ``False`` -caso contrário. - -Aqui você tem uma função que irá retornar ``True`` se uma tag definir -o atributo `class`, mas não definir o atributo `id`:: - - def has_class_but_no_id(tag): - return tag.has_attr('class') and not tag.has_attr('id') - -Passe esta função dentro de ``find_all()`` e você irá retornar todas -as tags

:: - - soup.find_all(has_class_but_no_id) - # [

The Dormouse's story

, - #

Once upon a time there were...

, - #

...

] - -Esta função irá encontrar apenas as tags

. Não irá encontrar as tags , -porque elas definem "class e "id" ao mesmo tempo. Ela não encontrará -as tags e , porque estas tags não definem um atributo -"class". - -Se você passar uma função para filtrar um atributo específico como -``href``, o argumento passado na função será o nome do atributo e -não toda a tag. Aqui vemos uma função que encontra todas as tags <a> -em que o atributo ``href`` não corresponde a expressão regular passada:: - - def not_lacie(href): - return href and not re.compile("lacie").search(href) - soup.find_all(href=not_lacie) - # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, - # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] - -A função pode ser tão complexa quanto você precise que seja. -Aqui temos uma função que retorna ``True`` se uma tag esta -cercada por objetos string:: - - from bs4 import NavigableString - def surrounded_by_strings(tag): - return (isinstance(tag.next_element, NavigableString) - and isinstance(tag.previous_element, NavigableString)) - - for tag in soup.find_all(surrounded_by_strings): - print tag.name - # p - # a - # a - # a - # p - -Agora nós estamos prontos para olhar os métodos de busca em detalhes. - -``find_all()`` --------------- - -Definição: find_all(:ref:`name <name>`, :ref:`attrs <attrs>`, :ref:`recursive -<recursive>`, :ref:`string <string>`, :ref:`limit <limit>`, :ref:`**kwargs <kwargs>`) - -O método ``find_all()`` busca entre os decendentes de uma tag e retorna todos os decendentes -que correspondem a seus filtros. Dei diversos exemplos em `Tipos de filtros`_, -mas aqui estão mais alguns:: - - soup.find_all("title") - # [<title>The Dormouse's story] - - soup.find_all("p", "title") - # [

The Dormouse's story

] - - soup.find_all("a") - # [Elsie, - # Lacie, - # Tillie] - - soup.find_all(id="link2") - # [Lacie] - - import re - soup.find(string=re.compile("sisters")) - # u'Once upon a time there were three little sisters; and their names were\n' - -Alguns podem parecer familiares, mas outros são novos. -O que significa passar um valor ``string`` ou ``id``? Por que -``find_all("p", "title")`` encontra uma tag

com a classe CSS "title"? -Vamos dar uma olhada nos argumentos de ``find_all()``. - -.. _name: - -O argumento ``name`` -^^^^^^^^^^^^^^^^^^^^ - -Passe um valor para ``name`` e você dirá para o Beautiful Soup -considerar apenas as tags com certos nomes. Strings de texto seão ignoradas, -assim como os nomes que não corresponderem ao argumento ``name`` - -Este é o uso mais simples:: - - soup.find_all("title") - # [The Dormouse's story] - -Lembre-se de `Tipos de filtros`_ que o valor para ``name`` pode ser `uma -string`_, `uma expressão regular`_, `uma lista`_, `uma função`_, ou `o valor -True`_. - -.. _kwargs: - -Os argumentos "palavras-chave" -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Qualquer argumento que não for reconhecido se tornará um filtro -de atributos da tag. Se você passar um valor para um argumento -chamado ``id``, o Beautiful Soup irá buscar correspondentes entre -todas tags ``id``:: - - soup.find_all(id='link2') - # [Lacie] - -Se você passar um valor para ``href``, o Beautiful Soup buscar correspondentes -em cada tag que possua o atributo ``href``:: - - soup.find_all(href=re.compile("elsie")) - # [Elsie] - -Você pode filtrar um atributo baseado em `uma string`_, `uma regular -expression`_, `uma lista`_, `uma função`_, ou `no valor True`_. - -Este código encontra todas as tags em que o atributo ``id`` -possuem um valor, independente de qual valor seja:: - - soup.find_all(id=True) - # [Elsie, - # Lacie, - # Tillie] - -Você pode filtrar múltiplos atributos de uma vez passando mais de um argumento -palavra-chave:: - - soup.find_all(href=re.compile("elsie"), id='link1') - # [three] - -Alguns atributos, como o atributo data-* do HTML5, possuem nomes que não -podem ser usados como argumentos palavra-chave::: - - data_soup = BeautifulSoup('

foo!
') - data_soup.find_all(data-foo="value") - # SyntaxError: keyword can't be an expression - -Você pode usar estes atributos para realizar buscas, colocando-os -em um dicionário e passando o dicionário em ``find_all()``, como o argumento -``attrs``:: - - data_soup.find_all(attrs={"data-foo": "value"}) - # [
foo!
] - -Você não pode utilizar um argumento palavra-chave para buscar pelo elemento -HTML "name", porque o Beautiful Soup utiliza o argumento ``name`` para -conter o nome da própria tag. Ao invés disso, você pode passar o valor para -"name" no argumento ``attrs``:: - - name_soup = BeautifulSoup('') - name_soup.find_all(name="email") - # [] - name_soup.find_all(attrs={"name": "email"}) - # [] - -.. _attrs: - -Buscando por uma classe CSS -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -É muito útil buscar por uma tag que tem uma certa classe CSS, mas -o nome do atributo CSS, "class", é uma palavra reservada no Python. -Utilizar ``class`` como um argumento palavra-chave lhe trará um erro -de sintaxe. A partir do Beautiful Soup 4.1.2, você pode buscar por uma -classe CSS utilizando o argumento palavra-chave ``class_``:: - - soup.find_all("a", class_="sister") - # [Elsie, - # Lacie, - # Tillie] - -Assim como qualquer argumento palavra-chave, você pode passar para ``class_`` -uma string, uma expressão regular (regex), uma função ou ``True``:: - - soup.find_all(class_=re.compile("itl")) - # [

The Dormouse's story

] - - def has_six_characters(css_class): - return css_class is not None and len(css_class) == 6 - - soup.find_all(class_=has_six_characters) - # [Elsie, - # Lacie, - # Tillie] - -:ref:`Lembre-se ` que uma tag pode ter valores múltiplos -para seu atributo classe. Quando você buscar por uma tag que tenha -uma certa classe CSS, você esta buscando correspodência em `qualquer` -de suas classes CSS:: - - css_soup = BeautifulSoup('

') - css_soup.find_all("p", class_="strikeout") - # [

] - - css_soup.find_all("p", class_="body") - # [

] - -Você pode também buscar por uma string exata como valor de ``class``:: - - css_soup.find_all("p", class_="body strikeout") - # [

] - -Mas ao procurar por variações de uma string, isso não irá funcionar:: - - css_soup.find_all("p", class_="strikeout body") - # [] - -Se voce quiser buscar por tags que correspondem a duas ou mais classes CSS, -você deverá utilizar um seletor CSS:: - - css_soup.select("p.strikeout.body") - # [

] - -Em versões mais antigas do Beautiful Soup, as quais não possuem o atalho ``class_`` -você pode utilizar o truque ``attrs`` conforme mencionado acima. Será criado um dicionário -do qual o valor para "class" seja uma string ( ou uma expressão regular, ou qualquer -outra coisa) que você queira procurar:: - - soup.find_all("a", attrs={"class": "sister"}) - # [Elsie, - # Lacie, - # Tillie] - -.. _string: - -O argumento ``string`` -^^^^^^^^^^^^^^^^^^^^^^^ - -Com ``string`` você pode buscar por strings ao invés de tags. Assim como -``name`` e os argumentos palavras-chave, você pode passar `uma string`_, `uma -expressão regular`_, `uma lista`_, `uma função`_, ou `o valor True`_. -Aqui estão alguns exemplos:: - - soup.find_all(string="Elsie") - # [u'Elsie'] - - soup.find_all(string=["Tillie", "Elsie", "Lacie"]) - # [u'Elsie', u'Lacie', u'Tillie'] - - soup.find_all(string=re.compile("Dormouse")) - [u"The Dormouse's story", u"The Dormouse's story"] - - def is_the_only_string_within_a_tag(s): - """Return True if this string is the only child of its parent tag.""" - return (s == s.parent.string) - - soup.find_all(string=is_the_only_string_within_a_tag) - # [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...'] - -Mesmo que ``string`` seja para encontrar strings, você pode combiná-lo com argumentos -para encontrar tags: o Beautiful Soup encontrará todas as tags as quais -``.string`` corresponder seu valor em ``string``. O código seguinte encontra -a tag , a qual a ``.string`` é "Elsie":: - - soup.find_all("a", string="Elsie") - # [Elsie] - -O argumento ``string`` é novo no Beautiful Soup 4.4.0. Em versões anteriores -ele era chamado de ``text``:: - - soup.find_all("a", text="Elsie") - # [Elsie] - -.. _limit: - -O argumento ``limit`` -^^^^^^^^^^^^^^^^^^^^^^ - -``find_all()`` retorna todas as tags e strings que correspondem aos seus -filtros. Isso pode levar algum tmepo se o documento for extenso. Se você -não precisar de `todos` os resultados, você pode passar um número limite -(``limit``). Ele funciona assim como o parâmetro LIMIT utilizado em SQL. -Ele diz ao Beautiful Soup para parar de adquirir resultados assim que atingir -um certo número. - -Existem três links no documento "three sisters", mas este código encontra somente -os dois primeiros:: - - soup.find_all("a", limit=2) - # [Elsie, - # Lacie] - -.. _recursive: - -O argumento ``recursive`` -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Se você chamar ``mytag.find_all()``, o Beautiful Soup irá examinar todos os descendentes -de ``mytag``: suas filhas, as filhas de suas filhas e daí em diante. Se você quer apenas que -o Beautiful Soup considere filhas diretas, você pode passar o parâmetro ``recursive=False``. -Veja a diferença aqui:: - - soup.html.find_all("title") - # [The Dormouse's story] - - soup.html.find_all("title", recursive=False) - # [] - -Aqui está o trecho do documento:: - - - - - The Dormouse's story - - - ... - -O tag esta abaixo da tag <html>, mas não está `diretamente` -abaixo de <html>: a tag <head> está no caminho entre elas. O Beautiful Soup encontra a tag -<title> quando é autorizado a olhar todos os descendentes de <html>, mas -quando ``recursive=False`` é restringido o acesso as filhas imediatas de <html>. - -O Beautiful Soup oferece diversos métodos de busca na árvore (como vimos acima), e a maioria -deles recebe os mesmos argumentos que ``find_all()``: ``name``, -``attrs``, ``string``, ``limit``, e os argumentos palavras-chave. Mas o -argumento ``recursive`` é diferente: ``find_all()`` e ``find()`` são -os únicos métodos que o suportam. Passar ``recursive=False`` em um método -como ``find_parents()`` não seria muito útil. - -Chamar uma tag é como chamar ``find_all()`` --------------------------------------------- - -Por ``find_all()`` ser o método mais popular na API de busca do -Beautiful Soup, você pode usar um atalho para ele. Se você tratar -o objeto ``BeautifulSoup`` ou um objeto ``Tag`` como se fosse uma -função, então é o mesmo que chamar ``find_all()`` para aquele objeto. -Estas duas linhas de código são equivalentes:: - - soup.find_all("a") - soup("a") - -Estas duas linhas também são equivalentes:: - - soup.title.find_all(string=True) - soup.title(string=True) - -``find()`` ----------- - -Signature: find(:ref:`name <name>`, :ref:`attrs <attrs>`, :ref:`recursive -<recursive>`, :ref:`string <string>`, :ref:`**kwargs <kwargs>`) - -O método ``find_all()`` varre todo o documento em busca de resultados, -mas algumas vezes você irá querer apenas um resultado. Se você sabe que -o documento possui apenas uma tag <body>, é perda de tempo varrer todo o -o documento procurando por outras. Ao invés de passar ``limit=1`` -toda vez em que chamar ``find_all``, você pode usar o método ``find()``. -Estas duas linhas de código são `quase` equivalentes:: - - soup.find_all('title', limit=1) - # [<title>The Dormouse's story] - - soup.find('title') - # The Dormouse's story - -A única diferença é que ``find_all()`` retorna uma lista contendo apenas -um resuldado, enquanto ``find()`` retorna o resultado. - -Se ``find_all()`` não encontrar nada, ele retornará uma lista vazia. Se -``find()`` não encontrar nada, ele retornará ``None``:: - - print(soup.find("nosuchtag")) - # None - -Lembre-se do truque ``soup.head.title`` de `Navegar usando os nomes das tags`_? -Aquele truque funciona chamando repetidamente ``find()``:: - - soup.head.title - # The Dormouse's story - - soup.find("head").find("title") - # The Dormouse's story - -``find_parents()`` e ``find_parent()`` ----------------------------------------- - -Signature: find_parents(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) - -Signature: find_parent(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) - -Levei muito tempo cobrindo ``find_all()`` e ``find()`` acima. -O API do Beautiful Soup define dez outros métodos -para buscas na árvore, mas não tenha medo! Cinco destes métodos são -basicamente o mesmo que ``find_all()``, e os outros cinco são basicamente -o mesmo que ``find()``. A única diferença está em qual parte da árvore -eles procuram. - -Primeiro vamos considerar ``find_parents()`` e -``find_parent()``. Lembre-se que ``find_all()`` e ``find()`` trabalham -de sua própria maneira descendo através da árvore, procurando pelos -descendentes de uma tag. Estes métodos fazem o contrário: eles trabalham -`subindo` a árvore, procurando pelas `mães` de uma tag (ou string). -Vamos experimentá-los: começando por uma string "enterrada" no documento -"three daughters":: - - a_string = soup.find(string="Lacie") - a_string - # u'Lacie' - - a_string.find_parents("a") - # [Lacie] - - a_string.find_parent("p") - #

Once upon a time there were three little sisters; and their names were - # Elsie, - # Lacie and - # Tillie; - # and they lived at the bottom of a well.

- - a_string.find_parents("p", class="title") - # [] - -Uma das três tags é diretamente um nível superior da string em -questão, então nossa busca a encontra. Uma das três tags

é uma mãe -indireta da string e nossa busca também a encontra. Há uma tag

com -a classe CSS "title" em algum lugar no documento, mas não é nenhuma das tags mães -da string, portanto, não podemos encontrá-la com ``find_parents()``. - -Você já deve ter feito a conexão entre ``find_parent()`` e -``find_parents()``, e os atributos `.parent`_ e `.parents`_ mencionados -anteriormente. A conexão é muito forte. Estes métodos de busca utilizam ``.parents`` -para iterar sobre todos as mãesS e compara cada um com o filtro passado -para verificar se preenche o requisito. - -``find_next_siblings()`` e ``find_next_sibling()`` ----------------------------------------------------- - -Signature: find_next_siblings(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) - -Signature: find_next_sibling(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) - -Estes métodos utilizam :ref:`.next_siblings ` para -iterar sobre o resto dos filhos de um elemento da árvore. O método -``find_next_siblings()`` retornará todos os filhos que atendem o -requisito ``find_next_sibling()`` retorna apenas o primeiro:: - - first_link = soup.a - first_link - # Elsie - - first_link.find_next_siblings("a") - # [Lacie, - # Tillie] - - first_story_paragraph = soup.find("p", "story") - first_story_paragraph.find_next_sibling("p") - #

...

- -``find_previous_siblings()`` e ``find_previous_sibling()`` ------------------------------------------------------------- - -Signature: find_previous_siblings(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) - -Signature: find_previous_sibling(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) - -Estes métodos utilizam :ref:`.previous_siblings ` para iterar sobre os filhos de um elemento que -o precede na árvore. O método ``find_previous_siblings()`` -retorna todos os filhos que atendem o requisito e ``find_previous_sibling()``retorna apenas o primeiro:: - - last_link = soup.find("a", id="link3") - last_link - # Tillie - - last_link.find_previous_siblings("a") - # [Lacie, - # Elsie] - - first_story_paragraph = soup.find("p", "story") - first_story_paragraph.find_previous_sibling("p") - #

The Dormouse's story

- - -``find_all_next()`` e ``find_next()`` ---------------------------------------- - -Signature: find_all_next(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) - -Signature: find_next(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) - -Estes métodos utilizam :ref:`.next_elements ` para -iterar sobre qualquer tag e string que aparecer depois da atual no documento. -O método ``find_all_next()`` retorna todos os casos que atendem, e -``find_next()`` retorna somente o primeiro caso:: - - first_link = soup.a - first_link - # Elsie - - first_link.find_all_next(string=True) - # [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'] - - first_link.find_next("p") - #

...

- -No primeiro exemplo, a string "Elsie" foi encontrada, mesmo estando -dentro da tag . No segundo exemplo, a última tag

do documento foi -encontrada, mesmo que não esteja na mesma parte da árvore que onde começamos. -Para estes métodos, o que importa é que um elemento corresponda ao filtro e esteja -depois do elemento de início no documento. - -``find_all_previous()`` e ``find_previous()`` ------------------------------------------------ - -Signature: find_all_previous(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`limit `, :ref:`**kwargs `) - -Signature: find_previous(:ref:`name `, :ref:`attrs `, :ref:`string `, :ref:`**kwargs `) - -Estes métodos utilizam :ref:`.previous_elements ` para -iterar sobre as tags e strings que aparecem antes do elemento indicado no argumento. -O método ``find_all_previous()`` retorna todos que correspondem a busca e o método -``find_previous()`` apenas a primeira correspondência:: - - first_link = soup.a - first_link - # Elsie - - first_link.find_all_previous("p") - # [

Once upon a time there were three little sisters; ...

, - #

The Dormouse's story

] - - first_link.find_previous("title") - # The Dormouse's story - -Quando se chama ``find_all_previous("p")`` é encontrado não só o -primeiro parágrafo do documento (o que possui class="title"), mas também o -segundo parágrafo, a tag

que contém a tag por onde começamos. -Isso não deveria ser tão surpreendente: nós estamos olhando para todas as tags -que apareceram anteriormente no documento incluindo aquela onde começamos. Uma -tag

que contenha uma tag deve aparecer antes da tag que ela contém. - -Seletores CSS -------------- - -A partir da versão 4.7.0, o Beautiful Soup suporta a maior parte dos seletores CSS4 -através do projeto `SoupSieve `_. Se você -instalou o Beautiful Soup através do ``pip``,o SoupSieve foi instalado ao mesmo tempo, -portanto você não precisará realizar nenhuma etapa adicional. - -``BeautifulSoup`` possui um método ``.select()`` o qual utiliza o SoupSieve para -executar um seletor CSS selector sobre um documento a ser analisado e retorna todos os -elementos correspondentes. ``Tag`` possui um método similar que executa um seletor CSS -sobre o conteúdo de uma única tag. - -(Versões anteriores do Beautiful Soup também possuem o método ``.select()``, - mas somente os seletores CSS mais populares são suportados. - -A `documentação `_ SoupSieve -lista todos os seletores suportados atualmente, mas aqui estão alguns dos -básicos:: - -Você pode encontrar tags:: - - soup.select("title") - # [The Dormouse's story] - - soup.select("p:nth-of-type(3)") - # [

...

] - -Encontrar tags aninhadas com outras:: - soup.select("body a") - # [Elsie, - # Lacie, - # Tillie] - - soup.select("html head title") - # [The Dormouse's story] - -Encontrar tags `diretamente` abaixo de outras tags no aninhamento:: - - soup.select("head > title") - # [The Dormouse's story] - - soup.select("p > a") - # [Elsie, - # Lacie, - # Tillie] - - soup.select("p > a:nth-of-type(2)") - # [Lacie] - - soup.select("p > #link1") - # [Elsie] - - soup.select("body > a") - # [] - -Encontrar as irmãs de alguma tag:: - - soup.select("#link1 ~ .sister") - # [Lacie, - # Tillie] - - soup.select("#link1 + .sister") - # [Lacie] - -Encontrar tags pela classe CSS:: - - soup.select(".sister") - # [Elsie, - # Lacie, - # Tillie] - - soup.select("[class~=sister]") - # [Elsie, - # Lacie, - # Tillie] - -Encontrar tags pelo ID:: - - soup.select("#link1") - # [Elsie] - - soup.select("a#link2") - # [Lacie] - -Encontrar tags que se relacionam com qualquer seletor em uma lista de seletores:: - - soup.select("#link1,#link2") - # [Elsie, - # Lacie] - -Testar a existência de um atributo:: - - soup.select('a[href]') - # [Elsie, - # Lacie, - # Tillie] - -Encontrar tags pelo valor do atributo:: - - soup.select('a[href="http://example.com/elsie"]') - # [Elsie] - - soup.select('a[href^="http://example.com/"]') - # [Elsie, - # Lacie, - # Tillie] - - soup.select('a[href$="tillie"]') - # [Tillie] - - soup.select('a[href*=".com/el"]') - # [Elsie] - -Há outro método chamado ``select_one()``, o qual encontra somente -a primeira tag que combina com um seletor:: - - soup.select_one(".sister") - # Elsie - -Se você analisou um XML que define namespaces, você pode -utilizar nos seletores CSS:: - - from bs4 import BeautifulSoup - xml = """ - I'm in namespace 1 - I'm in namespace 2 - """ - soup = BeautifulSoup(xml, "xml") - - soup.select("child") - # [I'm in namespace 1, I'm in namespace 2] - - soup.select("ns1|child", namespaces=namespaces) - # [I'm in namespace 1] - -Quando manipulando um seletor CSS que utiliza -namespaces,o Beautiful Soup utiliza a abreviação do namespace -que encontrou quando estava analisando o documento. Você pode evitar isso -passando um dicionário com suas próprias abreviações:: - - namespaces = dict(first="http://namespace1/", second="http://namespace2/") - soup.select("second|child", namespaces=namespaces) - # [I'm in namespace 2] - -Todo este negócio de seletor CSS é conveniente -para pessoas que já sabem a sintaxe do seletor CSS. -Você pode fazer tudo isso com a API do BeautifulSoup. -E se os seletores CSS são tudo o que você precisa, -você deveria analisar o documento com lxml: é mais rápido. Mas isso deixa você `combinar` -seletores CSS com a API do Beautiful Soup. - -Modificando a árvore -==================== - -O principal poder do Beautiful Soup está na busca pela árvore, mas você -pode também modificar a árvore e escrever suas modificações como um novo -documento HTML ou XML. - -Alterando nomes de tags e atributos ---------------------------------- - -Cobri este assunto anteriormente em `Atributos`_, mas vale a pena repetir. Você -pode renomear uma tag, alterar o valor de algum de seus atributos, adicionar novos -atributos e deletar qualquer um deles:: - - soup = BeautifulSoup('Extremely bold') - tag = soup.b - - tag.name = "blockquote" - tag['class'] = 'verybold' - tag['id'] = 1 - tag - #
Extremely bold
- - del tag['class'] - del tag['id'] - tag - #
Extremely bold
- -Modificando ``.string`` ------------------------ - -Se você definir o um atributo ``.string`` de uma tag, o conteúdo da -tag será substituido pela string que foi passada:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - - tag = soup.a - tag.string = "New link text." - tag - # New link text. - -Cuidado: se a tag conter outra(s) tag(s), ela(s) e todo seu conteúdo -serão destruídos. - -``append()`` ------------- - -Você pode adicionar algo no conteúdo de uma tag com ``Tag.append()``. Funciona -da mesma maneira que ``.append()`` de uma lista:: - - soup = BeautifulSoup("Foo") - soup.a.append("Bar") - - soup - # FooBar - soup.a.contents - # [u'Foo', u'Bar'] - -``extend()`` ------------- - -Com início no Beautiful Soup 4.7.0, ``Tag`` também suporta um método chamado -``.extend()``, o qual funciona da mesma maneira que chamando ``.extend()`` em -uma lista:: - - soup = BeautifulSoup("Soup") - soup.a.extend(["'s", " ", "on"]) - - soup - # Soup's on - soup.a.contents - # [u'Soup', u''s', u' ', u'on'] - -``NavigableString()`` e ``.new_tag()`` -------------------------------------------------- - -Se você precisar adicionar uma string a um documento, sem problema -- você -pode passar uma string Python através de ``append()``, ou você pode chamar -o construtor ``NavigableString``:: - - soup = BeautifulSoup("") - tag = soup.b - tag.append("Hello") - new_string = NavigableString(" there") - tag.append(new_string) - tag - # Hello there. - tag.contents - # [u'Hello', u' there'] - -Se você quiser criar um comentário ou alguma outra subclasse de -``NavigableString``, apenas chame o construtor:: - - from bs4 import Comment - new_comment = Comment("Nice to see you.") - tag.append(new_comment) - tag - # Hello there - tag.contents - # [u'Hello', u' there', u'Nice to see you.'] - -(Esta é uma funcionalidade nova no Beautiful Soup 4.4.0.) - -E se você precisar criar uma nova tag? A melhor solução -é chamar o método ``BeautifulSoup.new_tag()``:: - - soup = BeautifulSoup("") - original_tag = soup.b - - new_tag = soup.new_tag("a", href="http://www.example.com") - original_tag.append(new_tag) - original_tag - # - - new_tag.string = "Link text." - original_tag - # Link text. - -Somente o primeiro argumento (o nome da tag) é obrigatório. - -``insert()`` ------------- - -``Tag.insert()`` funciona assim como ``Tag.append()``, exceto que o novo elemento -não será inserido ao final do ``.contents`` de sua tag mãe. Ele será inserido em qualquer posição -numérica que você informar. Funciona assim como ``.insert()`` em uma lista:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - tag = soup.a - - tag.insert(1, "but did not endorse ") - tag - # I linked to but did not endorse example.com - tag.contents - # [u'I linked to ', u'but did not endorse', example.com] - -``insert_before()`` e ``insert_after()`` ------------------------------------------- - -O método ``insert_before()`` insere tags ou strings imediatamente antes de algo -na árvore:: - - soup = BeautifulSoup("stop") - tag = soup.new_tag("i") - tag.string = "Don't" - soup.b.string.insert_before(tag) - soup.b - # Don'tstop - -O método ``insert_after()`` insere tags ou strings imediatamente após algo -na árvore:: - - div = soup.new_tag('div') - div.string = 'ever' - soup.b.i.insert_after(" you ", div) - soup.b - # Don't you
ever
stop
- soup.b.contents - # [Don't, u' you',
ever
, u'stop'] - -``clear()`` ------------ - -O ``Tag.clear()`` remove o conteúdo de uma tag:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - tag = soup.a - - tag.clear() - tag - # - -``extract()`` -------------- - -O ``PageElement.extract()`` remove uma tag ou string da árvore. Ele retorna -a tag ou string que foi extraída:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - a_tag = soup.a - - i_tag = soup.i.extract() - - a_tag - # I linked to - - i_tag - # example.com - - print(i_tag.parent) - None - -Neste ponto você efetivamente tem duas árvores de análise: uma baseada no objeto -``BeautifulSoup`` que você usou para analisar o documento, e outra baseada na tag que foi -extraída. Você pode também chamar ``extract`` em um filho do elemento que você extraiu:: - - my_string = i_tag.string.extract() - my_string - # u'example.com' - - print(my_string.parent) - # None - i_tag - # - - -``decompose()`` ---------------- - -O ``Tag.decompose()`` remove uma tag da árvore, então destrói `completamente` ela -e seu conteúdo:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - a_tag = soup.a - - soup.i.decompose() - - a_tag - # I linked to - - -.. _replace_with(): - -``replace_with()`` ------------------- - -Um ``PageElement.replace_with()`` remove uma tag ou string da árvore e -substitui pela tag ou string que você escolher:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - a_tag = soup.a - - new_tag = soup.new_tag("b") - new_tag.string = "example.net" - a_tag.i.replace_with(new_tag) - - a_tag - # I linked to example.net - -``replace_with()`` retorna a tag ou string que foi substituída, então você pode -examiná-la ou adicioná-la novamente em outra parte da árvore. - -``wrap()`` ----------- - -O ``PageElement.wrap()`` envelopa um elemento na tag que você especificar. Ele -retornará o novo empacotador:: - - soup = BeautifulSoup("

I wish I was bold.

") - soup.p.string.wrap(soup.new_tag("b")) - # I wish I was bold. - - soup.p.wrap(soup.new_tag("div") - #

I wish I was bold.

- -Este método é novo no Beautiful Soup 4.0.5. - -``unwrap()`` ---------------------------- - -O ``Tag.unwrap()`` é o oposto de ``wrap()``. Ele substitui uma tag pelo -que estiver dentro dela. É uma boa maneira de remover marcações:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - a_tag = soup.a - - a_tag.i.unwrap() - a_tag - # I linked to example.com - -Assim como ``replace_with()``, ``unwrap()`` retorna a tag que foi -substituída. - -``smooth()`` ---------------------------- - -Após chamar vários métodos que modificam a árvore, você pode acabar com um ou dois objetos ``NavigableString`` próximos um ao outro. O Beautiful Soup não tem nenhum problema com isso, mas como isso não pode acontecer em um documento que acabou de ser analisado, você não deve esperar um comportamento como o seguinte:: - - soup = BeautifulSoup("

A one

") - soup.p.append(", a two") - - soup.p.contents - # [u'A one', u', a two'] - - print(soup.p.encode()) - #

A one, a two

- - print(soup.p.prettify()) - #

- # A one - # , a two - #

- -Você pode chamar ``Tag.smooth()`` para limpar a árvore analisada, consolidando strings adjacentes:: - - soup.smooth() - - soup.p.contents - # [u'A one, a two'] - - print(soup.p.prettify()) - #

- # A one, a two - #

- -O método ``smooth()`` é novo no Beautiful Soup 4.8.0. - -Saída -====== - -.. _.prettyprinting: - -Pretty-printing ---------------- - -O método ``prettify()`` irá transformar uma árvore do Beautiful Soup em -uma string Unicode devidamente formatada, com uma linha para cada tag e cada string:: - - markup = 'I linked to example.com' - soup = BeautifulSoup(markup) - soup.prettify() - # '\n \n \n \n \n...' - - print(soup.prettify()) - # - # - # - # - # - # I linked to - # - # example.com - # - # - # - # - -Você pode chamar ``prettify()`` no top-level do objeto ``BeautifulSoup``, -ou em qualquer de seus objetos ``Tag``:: - - print(soup.a.prettify()) - # - # I linked to - # - # example.com - # - # - -Non-pretty printing -------------------- - -Se você quer apenas uma string, sem nenhuma formatação, você pode chamar -``unicode()`` ou ``str()`` para o objeto ``BeautifulSoup`` ou uma ``Tag`` -dentro dele:: - - str(soup) - # 'I linked to example.com' - - unicode(soup.a) - # u'I linked to example.com' - -A função ``str()`` retorna uma string codificada em UTF-8. Veja -`Encodings`_ para outras opções. - -Você também pode chamar ``encode()`` para ter uma bytestring, e ``decode()`` -para ter Unicode. - -.. _output_formatters: - -Output formatters ------------------ - -Se você der para o Beautiful Soup um documento que contém entidades HTML como -"&lquot;", elas serão convertidades em caracteres Unicode:: - - soup = BeautifulSoup("“Dammit!” he said.") - unicode(soup) - # u'\u201cDammit!\u201d he said.' - -Se você converter o documento em uma string, os caracteres Unicode -serão codificados como UTF-8. Você não irá ter suas entidades HTML de volta:: - - str(soup) - # '\xe2\x80\x9cDammit!\xe2\x80\x9d he said.' - -Por padrão, os únicos caracteres que escapam desta saída são o & e os sinais de <>. -Eles são convertidos em "&", "<", -e ">", com isso o Beautiful Soup não gera HTML e XML inválidos de maneira inadvertida. - - soup = BeautifulSoup("

The law firm of Dewey, Cheatem, & Howe

") - soup.p - #

The law firm of Dewey, Cheatem, & Howe

- - soup = BeautifulSoup('A link') - soup.a - # A link - -Você pode alterar este comportamento informando um valor para o argumento de -``formatter`` para ``prettify()``, ``encode()``, ou -``decode()``. Beautiful Soup reconhece cinco possiveis valores para ``formatter``. - -O padrão é ``formatter="minimal"``. Strings sempre serão processadas de maneira a garantir que o Beautiful Soup gere HTML/XML válidos:: - - french = "

Il a dit <<Sacré bleu!>>

" - soup = BeautifulSoup(french) - print(soup.prettify(formatter="minimal")) - # - # - #

- # Il a dit <<Sacré bleu!>> - #

- # - # - -Se você passar ``formatter="html"``, Beautiful Soup irá converter caracteres -Unicode para entidades HTML sempre que possível:: - - print(soup.prettify(formatter="html")) - # - # - #

- # Il a dit <<Sacré bleu!>> - #

- # - # - -Se você passar um ``formatter="html5"``, é o mesmo que ``formatter="html"``, -mas o Beautiful Soup irá omitir a barra de fechamento HTML:: - - soup = BeautifulSoup("
") - - print(soup.encode(formatter="html")) - #
- - print(soup.encode(formatter="html5")) - #
- -Se você passar ``formatter=None``, Beautiful Soup não irá modificar -as strings na saída. Esta é a opção mais rápida, mas permitirá que o -Beautiful Soup gere HTML/XML inválidos, como nestes exemplos:: - - print(soup.prettify(formatter=None)) - # - # - #

- # Il a dit <> - #

- # - # - - link_soup = BeautifulSoup('A link') - print(link_soup.a.encode(formatter=None)) - # A link - -Se você precisar de controles mais sofisticados sobre sua saída, -você pode usar a classe ``Formatter`` do Beautiful Soup. Aqui você pode ver um -formatter que converte strings para uppercase, quando elas ocorrem em um nó de texto -ou em um valor de algum atributo:: - - from bs4.formatter import HTMLFormatter - def uppercase(str): - return str.upper() - formatter = HTMLFormatter(uppercase) - - print(soup.prettify(formatter=formatter)) - # - # - #

- # IL A DIT <> - #

- # - # - - print(link_soup.a.prettify(formatter=formatter)) - # - # A LINK - # - -Dividindo em subclasses ``HTMLFormatter`` ou ``XMLFormatter`` darão a você ainda -mais controle sobre a saída. Por exemplo, o Beautiful Soup ordena os atributos em toda -tag por padrão:: - - attr_soup = BeautifulSoup(b'

') - print(attr_soup.p.encode()) - #

- -Para desabilitar esta opção, você pode criar uma subclasse do método ``Formatter.attributes()``, -o qual controla qual atributo será usado na saída e em que ordem. Esta -implementação também filtra o atributido chamado "m" quando ele aparece:: - - class UnsortedAttributes(HTMLFormatter): - def attributes(self, tag): - for k, v in tag.attrs.items(): - if k == 'm': - continue - yield k, v - print(attr_soup.p.encode(formatter=UnsortedAttributes())) - #

- -Um último conselho: se você criar um objeto ``CDATA'', o texto dentro deste objeto -sempre estará presente `exatamente como aparenta, com nenhuma formatação`. -O Beautiful Soup irá chamar sua função de substituição da entidade, apenas -no caso de você ter escrito uma função personalizada que conta todas as strings -que existem no documento ou algo do tipo, mas ele irá ignorar o valor de retorno:: - - from bs4.element import CData - soup = BeautifulSoup("") - soup.a.string = CData("one < three") - print(soup.a.prettify(formatter="xml")) - # - # - # - - -``get_text()`` --------------- - -Se você quer apenas o texto contido no documento ou em um par de tags, você -pode utilizar o método ``get_text()``. Ele retornará todo texto em um documento -ou dentro das tags como uma string Unicode:: - - markup = '\nI linked to example.com\n' - soup = BeautifulSoup(markup) - - soup.get_text() - u'\nI linked to example.com\n' - soup.i.get_text() - u'example.com' - -Você pode especificar uma string a ser usada para unir as partes do texto:: - - # soup.get_text("|") - u'\nI linked to |example.com|\n' - -Você pode dizer ao Beautiful Soup para excluir espaços em branco do início -e fim de cada parte de texto:: - - # soup.get_text("|", strip=True) - u'I linked to|example.com' - -Contudo para isso, você pode querer utilizar o gerador :ref:`.stripped_strings ` -e processar o texto você mesmo:: - - [text for text in soup.stripped_strings] - # [u'I linked to', u'example.com'] - -Especificando um interpretador (parser) para uso -================================================ - -Se você precisa analisar um pequeno HTML, você pode passá-lo no construtor do -``BeautifulSoup`` e será o suficiente. O Beautiful Soup irá escolher um parser -para você e irá interpretar o dado. Mas existem alguns argumentos adicionais que você -pode passar no construtor para alterar qual parser será usado. - -O primeiro argumento do construtor ``BeautifulSoup`` é uma string ou uma variável contendo o -conteúdo do que você quer analisar. O segundo argumento é `como` você quer interpretar aquele -conteúdo. - -Se você não especificar nada, você irá utilizar o melhor analisador HTML instalado. -O Beautiful Soup classifica o lxml's como sendo o melhor, logo em seguida o html5lib, -e então o parser nativo do Python. Você pode substituí-lo, especificando de acordo -com as seguintes características: - -* O tipo de marcação que você quer analisar. Atualmente são suportados - "html", "xml", and "html5". -* O nome do parser que você quer utilizar. Atualmente são suportadas -as opções "lxml", "html5lib", e "html.parser" (parser nativo do Python). - -A seção `Instalando um interpretador (parser)`_ compara os parsers suportados. - -Se você não tem um parser apropriado instalado, o Beautiful Soup irá -ignorar sua solicitação e escolher um diferente. Atualmente, o único parser -XML suportado é o lxml. Se você não possui o lxml instalado, pedir um parser -XML não trará um e pedir por "lxml" não funcionará também. - -Diferenças entre os interpretadores (parsers) ------------------------------------------- - -O Beautiful Soup apresenta a mesma interface para diferentes parsers, -mas cada um é diferente. Diferentes parsers irão criar diferentes análises da árvore -do mesmo documento. As maiores diferenças estão entre os parsers HTML e XML. -Aqui está um pequeno documento analisado como HTML:: - - BeautifulSoup("") - # - -Como uma tag vazia não é um HTML válido, o analisador a transforma -em um par . - -Aqui está o mesmo documento analisado como XML (partindo do princípio -que você tenha o lxml instalado). Note que o a tag vazia é deixada sozinha, -e que é dada ao documento uma declaração XML ao invés de ser colocada dentro de uma tag .:: - - BeautifulSoup("", "xml") - # - # - -Há também diferenças entre analisadores HTML. Se você der ao Beautiful -Soup um documento HTML perfeitamente formatado, estas diferenças não irão -importar. Um analisador será mais rápido que outro, mas todos irão lhe -retornar uma estrutura de dados que se parece exatamente como o HTML original. - -Mas se o documento não estiver perfeitamente formatado, diferentes analisadores -irão retornar diferentes resultados. Aqui está um pequeno e inválido documento -analisado utilizando o analisador lxml HTML. Note que a tag pendente

é -simplesmente ignorada:: - - BeautifulSoup("

", "lxml") - #
- -Aqui está o mesmo documento analisado utilizando html5lib:: - - BeautifulSoup("

", "html5lib") - #

- -Ao invés de ignorar a tag

pendente, o html5lib a equipara a uma tag -

aberta. Este parser também adiciona uma tag vazia ao documento. - -Aqui está o mesmo documento analisado com o parser HTML nativo do Python:: - - BeautifulSoup("

", "html.parser") - # - -Assim como html5lib, este parser ignora a tag de fechamento

. -Este parser também não realiza nenhuma tentatida de criar um HTML bem -formatado adicionando uma tag . Como lxml, ele nem se importa em -adicionar uma tag . - -Sendo o documento "

" inválido, nenhuma dessas técnicas é a maneira -"correta" de lidar com isso. O html5lib utiliza técnicas que são parte -do padrão HTML5, portanto vendo sendo definido como a maneira "mais correta", -mas todas as três técnicas são legítimas. - -Diferenças entre analisadores podem afetar o seu script. Se você está -planejando distribuir seu script para outras pessoas, ou rodá-lo em -múltiplas máquinas, você deve especificar o analisador no construtor -``BeautifulSoup``. Isso irá reduzir as chances de que seus usuários -analisem um documento de forma diferente da maneira como você analisou. - - -Codificação (Encoding) -====================== - -Todo documento HTML ou XML é escrito em uma codificação (encoding) específica como ASCII -ou UTF-8. Mas quando você carrega um documento no BeautifulSoup, você irá descobrir -que ele foi convertido para Unicode:: - - markup = "

Sacr\xc3\xa9 bleu!

" - soup = BeautifulSoup(markup) - soup.h1 - #

Sacré bleu!

- soup.h1.string - # u'Sacr\xe9 bleu!' - -Não é mágica (Seria bem legal que fosse). O BeautifulSoup utiliza uma -sub-biblioteca chamada `Unicode, Dammit`_ para detectar a codificação de -um documento e convertê-lo para Unicode. A codificação detectada automaticamente está -disponível como objeto ``.original_encoding`` atributo do objeto ``BeautifulSoup`` :: - - soup.original_encoding - 'utf-8' - -`Unicode, Dammit` acerta na maioria das vezes, mas pode errar em algumas. -Outras vezes acerta, porém somente após uma busca byte a byte no documento, -o leva muito tempo. Se você souber com antecedência a codificação, você poderá -evitar erros ou demora passando-o para o contrutor do ``BeautifulSoup`` -através de ``from_encoding``. - -Abaixo você tem um documento escrito em ISO-8859-8. O documento é tão -pequeno que o `Unicode, Dammit` não consegue verificar sua codificação -e acaba fazendo a identificação como ISO-8859-7:: - - markup = b"

\xed\xe5\xec\xf9

" - soup = BeautifulSoup(markup) - soup.h1 -

νεμω

- soup.original_encoding - 'ISO-8859-7' - -Podemos consertar isso passando a codificação correta com ``from_encoding``:: - - soup = BeautifulSoup(markup, from_encoding="iso-8859-8") - soup.h1 -

םולש

- soup.original_encoding - 'iso8859-8' - -Se você não sabe qual a codificação correta, mas você sabe que o -`Unicode, Dammit` está errado, você pode passar as opções excluentes -como ``exclude_encodings``:: - - soup = BeautifulSoup(markup, exclude_encodings=["ISO-8859-7"]) - soup.h1 -

םולש

- soup.original_encoding - 'WINDOWS-1255' - -Windows-1255 não é 100% correto, mas é um superconjunto compatível com -ISO-8859-8, portanto é mais próximo do ideal. (``exclude_encodings`` -é uma opção nova no Beautiful Soup 4.4.0.) - -Em casos raros (geralmente quando um documento UTF-8 contém texto escrito -em uma codificação completamente diferente), a única maneira de ser convertido para -Unicode é convertendo alguns caracteres com o caractere especial Unicode -"REPLACEMENT CHARACTER" (U+FFFD, �). Se o `Unicode, Dammit` precisar utilizá-lo, -ele será armazenado no atributo ``.contains_replacement_characters`` como -``True`` no ``UnicodeDammit`` ou objeto ``BeautifulSoup``. Isso deixa você ciente -que a representação Unicode não é uma representação exata do original - algum dado -foi perdido. Se um documento possui �, mas ``.contains_replacement_characters`` é ``False``, -você poderá concluir então que o � já estava ali originalmente e não representa dados -perdidos. - -Codificação de Saída --------------------- - -Quando um documento é gerado pelo Beautiful Soup, ele é gerado como UTF-8, -mesmo que o documento não for um UTF-8 de início. Aqui está um documento gerado -com codificação Latin-1:: - - markup = b''' - - - - - -

Sacr\xe9 bleu!

- - - ''' - - soup = BeautifulSoup(markup) - print(soup.prettify()) - # - # - # - # - # - #

- # Sacré bleu! - #

- # - # - -Note que a tag foi reescrita para refletir o fato que o documento -é agora um UTF-8. - -Se você não quiser um UTF-8, você pode passar a codificação desejada como parâmetro de -``prettify()``:: - - print(soup.prettify("latin-1")) - # - # - # - # ... - -Você também pode chamar encode() no objeto ``BeautifulSoup`` ou em qualquer elemento -do objeto, assim como se faz em uma string Python:: - - soup.p.encode("latin-1") - # '

Sacr\xe9 bleu!

' - - soup.p.encode("utf-8") - # '

Sacr\xc3\xa9 bleu!

' - -Qualquer caractere que não pode ser representado na codificação escolhida -irá ser convertida para uma entidade de referência numérica XML. Abaixo você -tem um documento que inclui o caractere Unicode SNOWMAN:: - - markup = u"\N{SNOWMAN}" - snowman_soup = BeautifulSoup(markup) - tag = snowman_soup.b - -O caractere SNOWMAN faz parte da documentação UTF-8 (algo como -☃), mas não possui representação para este caractere em ISO-latin-1 ou -ASCII, portanto ele é convertido para "☃" para as essas codificações:: - - print(tag.encode("utf-8")) - # - - print tag.encode("latin-1") - # - - print tag.encode("ascii") - # - -Unicode, Dammit ---------------- - -Você pode usar o `Unicode, Dammit` fora do Beautiful Soup. É útil -quando você possui dados em uma codificação desconhecida e quer -simplesmente convertê-la para Unicode:: - - from bs4 import UnicodeDammit - dammit = UnicodeDammit("Sacr\xc3\xa9 bleu!") - print(dammit.unicode_markup) - # Sacré bleu! - dammit.original_encoding - # 'utf-8' - - -As respostas do `Unicode, Dammit` serão um pouco mais precisas se você -instalar as bibliotecas ``chardet`` ou ``cchardet``. Quanto maior a quantidade -de dados no arquivo que você passar para o `Unicode, Dammit`, mais precisas serão -as conversões. Se você possui suas suspeitas sobre qual a codificação original, -você pode passar as opções em uma lista:: - - dammit = UnicodeDammit("Sacr\xe9 bleu!", ["latin-1", "iso-8859-1"]) - print(dammit.unicode_markup) - # Sacré bleu! - dammit.original_encoding - # 'latin-1' - -`Unicode, Dammit` possui duas características que o Beautiful Soup não utiliza. - -Smart quotes -^^^^^^^^^^^^ - -Você pode utilizar `Unicode, Dammit` para converter Microsoft smart quotes para -entidades HTML ou XML:: - - markup = b"

I just \x93love\x94 Microsoft Word\x92s smart quotes

" - - UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="html").unicode_markup - # u'

I just “love” Microsoft Word’s smart quotes

' - - UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="xml").unicode_markup - # u'

I just “love” Microsoft Word’s smart quotes

' - -Você também pode converter Microsoft smart quotes para ASCII:: - - UnicodeDammit(markup, ["windows-1252"], smart_quotes_to="ascii").unicode_markup - # u'

I just "love" Microsoft Word\'s smart quotes

' - -Espero que você ache estas características úteis, mas o Beautiful Soup não -as usa.O Beautiful Soup dá preferência ao comportamento padrão, que é -converter para caracteres Unicode:: - - UnicodeDammit(markup, ["windows-1252"]).unicode_markup - # u'

I just \u201clove\u201d Microsoft Word\u2019s smart quotes

' - -Codificação Inconsistente -^^^^^^^^^^^^^^^^^^^^^^^^^ - -Algumas vezes um documento é em sua maioria UTF-8, mas contém caracteres -Windows-1252 assim como (de novo) Microsoft smart quotes. Isso pode acontecer -quando um website compostos de dados de muitas fontes diferentes. Você pode -utilizar ``UnicodeDammit.detwingle()`` para transformar este documento em um -UTF-8 puro. Aqui está um exemplo:: - - snowmen = (u"\N{SNOWMAN}" * 3) - quote = (u"\N{LEFT DOUBLE QUOTATION MARK}I like snowmen!\N{RIGHT DOUBLE QUOTATION MARK}") - doc = snowmen.encode("utf8") + quote.encode("windows_1252") - -Este documento é uma bagunça. O snowmen é um UTF-8 e as aspas são Windows-1252. -Você pode exibir o snowmen ou as aspas, mas não os dois ao mesmo tempo:: - - print(doc) - # ☃☃☃�I like snowmen!� - - print(doc.decode("windows-1252")) - # ☃☃☃“I like snowmen!” - -Decodificar um documento como UTF-8 gera um ``UnicodeDecodeError``, e -como um Windows-1252 lhe tras algo sem sentido. Felizmente, -``UnicodeDammit.detwingle()`` irá converter a string para UTF-8 puro, -permitindo a você decodificá-la para Unicode e exibir o snowmen e as -aspas simultaneamente:: - - new_doc = UnicodeDammit.detwingle(doc) - print(new_doc.decode("utf8")) - # ☃☃☃“I like snowmen!” - -``UnicodeDammit.detwingle()`` sabe apenas como trabalhar com Windows-1252 -contido em UTF-8 (ou vice versa, eu suponho), mas este é o caso mais comum. - -Note que você deve chamar ``UnicodeDammit.detwingle()`` em seu dado -antes de passá-lo para ``BeautifulSoup`` ou para o construtor ``UnicodeDammit``. -O Beautiful Soup assume que um documento possui apenas uma codificação, -independente de qual ela seja. Se você passar um documento que -contém ambos UTF-8 e Windows-1252, é provável que ele pense que todo -o documento seja Windows-1252, e o documento parecerá ``☃☃☃“I like snowmen!”``. - -``UnicodeDammit.detwingle()`` é novo no Beautiful Soup 4.1.0. - -Linhas numeradas -================ - -Os interpretadores ``html.parser` e ``html5lib`` podem rastrear onde, no -documento original, cada tag foi encontrada. Você pode acessar esta -informação através de ``Tag.sourceline`` (número da linha) e ``Tag.sourcepos`` -(posição do início da tag na linha):: - - markup = "Paragraph 1

\n

Paragraph 2

" - soup = BeautifulSoup(markup, 'html.parser') - for tag in soup.find_all('p'): - print(tag.sourceline, tag.sourcepos, tag.string) - # (1, 0, u'Paragraph 1') - # (2, 3, u'Paragraph 2') - -Note que os dois interpretadores significam coisas levemente diferentes por -``sourceline`` e ``sourcepos``. Para html.parser, estes números representam -a posição do sinal `menor que`inicial. Para html5lib, representa a posição -do sinal `maior que` final:: - - soup = BeautifulSoup(markup, 'html5lib') - for tag in soup.find_all('p'): - print(tag.sourceline, tag.sourcepos, tag.string) - # (2, 1, u'Paragraph 1') - # (3, 7, u'Paragraph 2') - -Você pode desabilitar esta característica passando ``store_line_numbers=False` -no construtor ``BeautifulSoup``:: - - markup = "Paragraph 1

\n

Paragraph 2

" - soup = BeautifulSoup(markup, 'html.parser', store_line_numbers=False) - soup.p.sourceline - # None - -Esta característica é nova no 4.8.1 e os analisadores baseados no lxml -não a suportam. - -Comparando objetos por igualdade -============================== - -O Beautiful Soup diz que dois objetos ``NavigableString`` ou ``Tag`` são -iguais quando eles apresentam as mesma marcação HTML ou XML. No exemplo -abaixo, as duas tags são tratadas como iguais, mesmo estando em partes -diferentes da árvore do objeto, porque ambas estão como "pizza":: - - markup = "

I want pizza and more pizza!

" - soup = BeautifulSoup(markup, 'html.parser') - first_b, second_b = soup.find_all('b') - print first_b == second_b - # True - - print first_b.previous_element == second_b.previous_element - # False - -Se você quiser verificar se duas variáveis se referem exatamente ao -mesmo objeto, use `is`:: - - print first_b is second_b - # False - -Copiando objetos Beautiful Soup -=============================== - -Você pode utilizar ``copy.copy()`` para criar uma cópia de qualquer ``Tag`` ou -``NavigableString``:: - - import copy - p_copy = copy.copy(soup.p) - print p_copy - #

I want pizza and more pizza!

- - -A cópia será considerada igual ao original, desde que ela apresente a mesma -marcação que o original, mas não será o mesmo objeto:: - - print soup.p == p_copy - # True - - print soup.p is p_copy - # False - -A única diferença real é que a cópia é completamente separada da árvore -original do Beautiful Soup, como se ``extract()`` fosse chamado para ela:: - - print p_copy.parent - # None - -Isso acontece porque dois objetos ``Tag`` diferentes não podem ocupar o mesmo -espaço ao mesmo tempo. - - -Analisando apenas parte de um documento -======================================= - -Suponhamos que você queira que o Beautiful Soup olhe apenas para as -tags
de um documento. É um desperdício de tempo e memória analisar -todo o documento e, posteriormente, analisar novamente apenas para buscar -as tags . Seria muito mais rápido ignorar tudo o que não for em -primeiro lugar. A classe ``SoupStrainer`` permite que você escolha -qual partes do documento serão analisadas. Você deverá penas criar uma -instância de ``SoupStrainer`` e passá-la ao construtor ``BeautifulSoup`` -no argumento ``parse_only``. - -(Note que *esta característica não funcionará se você estiver utilizando -o html5lib*. Se você utilizar o html5lib, todo o documento será analisado. -Isso acontece porque html5lib constantemente reorganiza a árvore de análise -e se alguma parte do documento realmente não fizer parte dela, ela irá quebrar. -Para evitar confusão, no exemplo abaixo, forçarei o Beautiful Soup a usar o -analisador nativo do Python). - -``SoupStrainer`` ----------------- - -A classe ``SoupStrainer`` recebe os mesmos argumentos que qualquer método em `Buscando na árvore`_: :ref:`name `, :ref:`attrs -`, :ref:`string `, e :ref:`**kwargs `. Aqui temos três objetos ``SoupStrainer`` :: - - from bs4 import SoupStrainer - - only_a_tags = SoupStrainer("a") - - only_tags_with_id_link2 = SoupStrainer(id="link2") - - def is_short_string(string): - return len(string) < 10 - - only_short_strings = SoupStrainer(string=is_short_string) - -Irei trazer de volta o documento "three sisters" mais uma vez e veremos -como o documento se parece quando é analisado com estes três objetos ``SoupStrainer` -diferentes:: - - html_doc = """ - The Dormouse's story - -

The Dormouse's story

- -

Once upon a time there were three little sisters; and their names were - Elsie, - Lacie and - Tillie; - and they lived at the bottom of a well.

- -

...

- """ - - print(BeautifulSoup(html_doc, "html.parser", parse_only=only_a_tags).prettify()) - # - # Elsie - # - # - # Lacie - # - # - # Tillie - # - - print(BeautifulSoup(html_doc, "html.parser", parse_only=only_tags_with_id_link2).prettify()) - # - # Lacie - # - - print(BeautifulSoup(html_doc, "html.parser", parse_only=only_short_strings).prettify()) - # Elsie - # , - # Lacie - # and - # Tillie - # ... - # - -Você pode também passar um ``SoupStrainer`` em qualquer método coberto em `Buscando na árvore`_. -Este uso provavelmente não seja muito útil, mas pensei que deveria mencioná-lo:: - - soup = BeautifulSoup(html_doc) - soup.find_all(only_short_strings) - # [u'\n\n', u'\n\n', u'Elsie', u',\n', u'Lacie', u' and\n', u'Tillie', - # u'\n\n', u'...', u'\n'] - -Solucionando Problemas -====================== - -.. _diagnose: - -``diagnose()`` --------------- - -Se você está tendo problemas em entender o que o Beautiful Soup está -fazendo com um documento, passe o documento pela função ``diagnose()``. (Nova no Beautiful Soup 4.2.0.) -O Beautiful Soup irá retornar um relatório mostrando como diferentes parsers -lidam com o documento e irá lhe dizer o Beautiful Soup poderia estar utilizando outro parser:: - - from bs4.diagnose import diagnose - with open("bad.html") as fp: - data = fp.read() - diagnose(data) - - # Diagnostic running on Beautiful Soup 4.2.0 - # Python version 2.7.3 (default, Aug 1 2012, 05:16:07) - # I noticed that html5lib is not installed. Installing it may help. - # Found lxml version 2.3.2.0 - # - # Trying to parse your data with html.parser - # Here's what html.parser did with the document: - # ... - -Olhando para o que diagnose() retorna, poderá lhe dizer como resolver -o seu problema. Mesmo que não consiga, você poderá colar a saída de ``diagnose()`` -quando solicitar ajuda. - -Erros enquanto se analisa um documento --------------------------------------- - -Existem dois tipos diferentes de erros de análise. Existem quebras -quando você passa para o Beautiful Soup um documento e ele retorna uma -exceção, geralmente um ``HTMLParser.HTMLParseError``. E existe o comportamento -inesperado, quando uma árvore de análise parece um pouco diferente do -documento usado para criá-la. - -Quase nenhum destes problemas são parte do Beautiful Soup. Não é -porque o Beautiful Soup é maravilhosamente um software bem escrito. É -porque o Beautiful Soup não inclui nenhum código de análise. Ao invés disso, -ele depende de analisadores externos. Se um analisador não funciona com -certo documento, a melhor solução é tentar um analisador diferente. Veja -`Instalando um analisador`_ para detalhes e uma comparação entre eles. - -Os erros de interpretação mais comuns são ``HTMLParser.HTMLParseError: - -malformed start tag`` e ``HTMLParser.HTMLParseError: bad end -tag``. Existem dois parsers gerados para o parser built in do Python -e a solução é :ref:`install lxml ou html5lib. ` - -Os tipos de erros de comportamento inesperado mais comuns acontecem -quando não é encontrada a tag buscada no documento. Você vê a busca -sendo executada, mas ``find_all()`` retorna ``[]`` ou ``find()`` retorna ``None``. -Este é um problema comum com o analisador HTML nativo do Python que algumas -vezes pula tags que ele não entende. Novamente, a solução é -:ref:`instalar o lxml ou html5lib.` - -Problemas de incompatibilidade de versões ------------------------------------------ - -* ``SyntaxError: Invalid syntax`` (on the line ``ROOT_TAG_NAME = - u'[document]'``): Causado por rodar a versão Python 2 do - Beautiful Soup no Python 3, sem converter o código. - -* ``ImportError: No module named HTMLParser`` - Causado por rodar a - versão Python 2 do Beautiful Soup no Python 3. - -* ``ImportError: No module named html.parser`` - Causado por rodar a - versão Python 3 do Beautiful Soup no Python 2. - -* ``ImportError: No module named BeautifulSoup`` - Causado por rodar - código do Beautiful Soup 3 em um sistema que não possui o BS3 - instalado. Ou por escrever código Beautiful Soup 4 sem saber que - o nome do pacote é diferente no ``bs4``. - -* ``ImportError: No module named bs4`` - Causado por rodar código Beautiful - Soup 4 em um sistema que não possui o BS4 instalado. - -.. _parsing-xml: - -Analisando um XML ------------------ - -Por padrão, o Beautiful Soup analisa documento como HTML. Para analisar um documento -como XML, passe "xml" como um segundo argumento ao construtor ``BeautifulSoup`` :: - - soup = BeautifulSoup(markup, "xml") - -Você precisará ter :ref:` lxml instalado `. - -Outros problemas com analisadores ---------------------------------- - -* Se seu script funciona em um computador, mas não em outro, - ou em um ambiente virtual mas não em outro, ou fora do ambiente - virtual mas não dentro dele, provavelmente porque ambos os ambientes - possuem bibliotecas de analisadores difererentes. Por exemplo, você pode - ter desenvolvido um script em um computador que possui lxml instalado, - e então estar tentando rodá-lo no seu computador que possui apenas html5lib - instalado. Veja :ref:`Diferenças entre os interpretadores (parsers)` para entender porque isso importa, - e corrija o problema mencionando uma biblioteca específica no construtor ``BeautifulSoup``. - -* Por tags `HTML e atributos serem case-insensitive - `_, todos os três - parsers HTML convertem tags e atributos para lowercase. Isso é, - a marcação é convertida para . Se você quiser - preservar a formatação anterior das tags e atributos, você precisará - :ref:`analisar o documento como XML. ` - -.. _misc: - -Diversos --------- - -* ``UnicodeEncodeError: 'charmap' codec can't encode character - u'\xfoo' in position bar`` (ou qualquer outro - ``UnicodeEncodeError``) - Este não é um problema do Beautiful Soup. - Este problema poderá surgir em duas situações: a primeira quando você - tentar imprimir um caractere Unicode que seu console não sabe como - exibir. (Veja `Esta página na wiki do Python - `_ para saber mais.). A segunda, - quando você está gravando um arquivo e passa um caractere Unicode que - não é suportado pelo seu codificador padrão. Neste caso, a solução mais - simples é explicitamente converter a string Unicode em UTF-8 com - ``u.encode("utf8")``. - -* ``KeyError: [attr]`` - Caused by accessing ``tag['attr']`` quando a - tag em questão não define o atributo ``attr``. Os erros mais comuns são - ``KeyError: 'href'`` e ``KeyError: - 'class'``. Use ``tag.get('attr')`` se você não tem certeza se ``attr`` está - definido, assim como você faria em um dicionário Python. - -* ``AttributeError: 'ResultSet' object has no attribute 'foo'`` - Isso - geralmente ocorre quando você espera que ``find_all()`` retorne - uma única tag ou string. Mas ``find_all()`` retorn uma _lista_ de tags - e strings--um objeto ``ResultSet``. Você precisa iterar sobre a lista e - buscar ``.foo`` para cada um. Ou, se você realmente quiser apenas um resultado, - deverá usar ``find()`` ao invés de ``find_all()``. - -* ``AttributeError: 'NoneType' object has no attribute 'foo'`` - Isso - geralmente acontece quando é chamado ``find()`` e então se tenta acessar - o atributo `.foo`` o resultado. Mas no seu caso, ``find()`` não encontra nada, - então retorna ``None`` ao invés de retornar uma tag ou uma string. Você precisa - descobrir porque ``find()`` não está retornando nada. - -Melhorando a performance ------------------------- - -O Beautiful Soup nunca será tão rápido quanto os parsers em que -ele foi construido em cima. Se o tempo de resposta se tornar crítico, -se você estiver pagando por hora de uso de um computador ou se há -qualquer outra razão para que o tempo de processamento seja mais -valioso que o tempo de programação, você deve esquecer o Beautiful Soup -e trabalhar diretamente em cima do `lxml `_. - -Dito isso, existem algumas coisas que você pode fazer para acelerar o -Beautiful Soup. Se você não está utilizando o lxml como seu parser, -meu conselho é que o faça :ref:`start `. -O Beautiful Soup analisa documentos significativamente mais rápido -utilizando o lxml do que usando o html.parser ou html5lib. - -Você pode acelerar a detecção da codificação significativamente instalando -a biblioteca `cchardet `_ . - -`Analisando apenas parte do documento`_ não irá lhe poupar muito tempo de -análise, mas irá poupar muita memória e fará a `busca` no documento muito -mais rápida. - -Beautiful Soup 3 -================ - -O Beautiful Soup 3 é a versão anterior e não é mais desenvolvida -ativamente. Ela atualmente faz parte da maioria das distribuições -Linux: - -:kbd:`$ apt-get install python-beautifulsoup` - -Também está publicada no PyPi como ``BeautifulSoup``.: - -:kbd:`$ easy_install BeautifulSoup` - -:kbd:`$ pip install BeautifulSoup` - -Você também pode fazer o `download de um tarball do Beautiful Soup 3.2.0 -`_. - -Se você rodar ``easy_install beautifulsoup`` ou ``easy_install -BeautifulSoup``, mas seu código não funcionar, você instalou o Beautiful -Soup 3 por engano. Você precisa executar ``easy_install beautifulsoup4``. - -`A documentação do Beautiful Soup 3 está arquivada online -`_. - -Portabilidade de código para BS4 --------------------------------- - -A maioria dos códigos escritos em Beautiful Soup 3 irá funcionar no -Beautiful Soup 4 com uma pequena alteração. Tudo que você precisa -fazer é alterar o nome do pacote de ``BeautifulSoup`` para ``bs4``. Então:: - - from BeautifulSoup import BeautifulSoup - -deverá ser assim:: - - from bs4 import BeautifulSoup - -* Se for gerado um ``ImportError`` "No module named BeautifulSoup", o - problema é que você está tentando executar um código Beautiful Soup 3, - mas possui apenas o Beautiful Soup 4 instalado. - -* Se for gerado um ``ImportError`` "No module named bs4", o problema - é que você está tentando executar um código Beautiful Soup 4, mas - possui apenas o Beautiful Soup 3 instalado. - -Apesar do BS4 ser quase totalmente compativel com BS3, a maioria de seus -métodos foram depreciados e renomeados para atender o padrão `PEP 8 -`_. Existem muitas outras -renomeações e alterações, e algumas delas quebram esta compatibilidade. - -Aqui está o que você irá precisar saber para converter seu código BS3 para BS4: - -Você precisa de um interpretador (parser) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -O Beautiful Soup 3 utilizava o ``SGMLParser`` do Python, um módulo que -foi depreciado e removido no Python 3.0. O Beautiful Soup 4 utiliza o -``html.parser`` por padrão, mas você pode adicionar o lxml ou html5lib -e utilizá-los como alternativa. Veja `Instalando um interpretador (parser)`_ para -comparação. - -Como o ``html.parser`` não é o mesmo analisador que ``SGMLParser``, é possível -que o Beautiful Soup 4 retorne uma árvore de análise diferente da -gerada pelo Beautiful Soup 3 para as mesmas marcações. Se você trocar -``html.parser`` por lxml ou html5lib, você poderá descorbrir que a árvore também -mudará. Se isso acontecer, você precisará atualizar seu código para lidar com a -nova árvore. - -Nomes dos Métodos -^^^^^^^^^^^^^^^^^ - -* ``renderContents`` -> ``encode_contents`` -* ``replaceWith`` -> ``replace_with`` -* ``replaceWithChildren`` -> ``unwrap`` -* ``findAll`` -> ``find_all`` -* ``findAllNext`` -> ``find_all_next`` -* ``findAllPrevious`` -> ``find_all_previous`` -* ``findNext`` -> ``find_next`` -* ``findNextSibling`` -> ``find_next_sibling`` -* ``findNextSiblings`` -> ``find_next_siblings`` -* ``findParent`` -> ``find_parent`` -* ``findParents`` -> ``find_parents`` -* ``findPrevious`` -> ``find_previous`` -* ``findPreviousSibling`` -> ``find_previous_sibling`` -* ``findPreviousSiblings`` -> ``find_previous_siblings`` -* ``getText`` -> ``get_text`` -* ``nextSibling`` -> ``next_sibling`` -* ``previousSibling`` -> ``previous_sibling`` - -Alguns argumentos do construtor do Beautiful Soup foram renomeados pelas -mesmas razões: - -* ``BeautifulSoup(parseOnlyThese=...)`` -> ``BeautifulSoup(parse_only=...)`` -* ``BeautifulSoup(fromEncoding=...)`` -> ``BeautifulSoup(from_encoding=...)`` - -Eu renomeei um método para compatibilidade com Python 3: - -* ``Tag.has_key()`` -> ``Tag.has_attr()`` - -Eu renomeei um atributo para utilizar uma terminologia mais precisa: - -* ``Tag.isSelfClosing`` -> ``Tag.is_empty_element`` - -Eu renomeei três atributos para evitar utilizar palavras reservadas do -Python. Ao contrário das outras, estas alterações *não são compativeis com -versões anteriores.* Se você utilizar estes atributos no BS3, seu código -irá quebrar no BS4 até você corrigí-los. - -* ``UnicodeDammit.unicode`` -> ``UnicodeDammit.unicode_markup`` -* ``Tag.next`` -> ``Tag.next_element`` -* ``Tag.previous`` -> ``Tag.previous_element`` - -Geradores -^^^^^^^^^ - -Eu dei nomes aos geradores de acordo com o PEP-8 e transformei-os -em propriedades: - -* ``childGenerator()`` -> ``children`` -* ``nextGenerator()`` -> ``next_elements`` -* ``nextSiblingGenerator()`` -> ``next_siblings`` -* ``previousGenerator()`` -> ``previous_elements`` -* ``previousSiblingGenerator()`` -> ``previous_siblings`` -* ``recursiveChildGenerator()`` -> ``descendants`` -* ``parentGenerator()`` -> ``parents`` - -Então, ao invés de:: - - for parent in tag.parentGenerator(): - ... - -Você pode escrever:: - - for parent in tag.parents: - ... - -(Mas a versão antiga ainda funcionará.) - -Alguns dos geradores eram utilizados para gerar ``None`` após -finalizado e então parar. Isso era um bug. Agora os geradores -apenas param. - -Existem dois novos geradores, :ref:`.strings e -.stripped_strings `. ``.strings`` gera objetos -NavigableString, e ``.stripped_strings`` gera strings Python com -espaços em branco removidos. - -XML -^^^ -Não existe mais uma classe ``BeautifulStoneSoup`` para analisar XML. Para -analisar XML você deverá passar "xml" como segundo argumento ao construtor -``BeautifulSoup``. Pela mesma razão, o construtor ``BeautifulSoup`` não -reconhece mais o argumento ``isHTML``. - -A manipulação do Beautiful Soup's de tags XML vazias foi melhorada. -Anteriormente, quando você analisava um XML, deveria explicitamente -dizer quais tags seriam consideradas elementos de tag vazios. O -argumento ``selfClosingTags`` não é mais reconhecido. Ao invés disso, -o Beautiful Soup considera qualquer tag vazia como um elemento de tag vazia. -Se você adicionar uma filha a um elemento de tag vazia, ela deixará de ser vazia. - -Entidades -^^^^^^^^^ - -Uma entidade HTML ou XML de entrada é sempre convertida em -seu caractere Unicode correspondente. O Beautiful Soup 3 possuia -inúmeras maneiras redundantes de lidar com entidades, as quais foram -removidas. O construtor ``BeautifulSoup`` não reconhece mais os argumentos -``smartQuotesTo`` ou ``convertEntities``. (`Unicode, -Dammit`_ ainda possui ``smart_quotes_to``, mas seu padrão agora é converter -smart quotes em Unicode.) As constantes ``HTML_ENTITIES``, -``XML_ENTITIES``, e ``XHTML_ENTITIES`` foram removidas, desde que elas -se referiam a uma feature (transformar algumas, mas não todas as entidades -em caracteres Unicode) que não existe mais. -Se você quiser transformar caracteres Unicode novamente em entidades HTML -na saída, ao invés de transformá-las em caracteres UTF-8, você precisará -utilizar um :ref:`output formatter `. - -Variados -^^^^^^^^ - -:ref:`Tag.string <.string>` agora opera recursivamente. Se a tag A -contém apenas uma tag B e nada mais, então A.string é o mesmo que -B.string. (Anteriormente era None) - -`Atributos com múltiplos valores`_ como ``class`` possuem listas de strings -como valores e não strings. Isso deverá afetar a maneira que você buscará -por classes CSS. - -Se você passar um dos métodos ``find*``, ambos :ref:`string ` `e` -um argumento específico de uma tag como :ref:`name `, o Beautiful Soup -irá buscar por tags que atentem o seu critério de argumento específico e que -:ref:`Tag.string <.string>` atenda o valor para :ref:`string `. Isso -`não` irá encontrar as strings por si. Anteriormente, Beautiful Soup ignorava -o argumento específico de uma tag e olhava apenas para as strings. - -O construtor ``BeautifulSoup`` não reconhece mais o argumento `markupMassage`. -É agora responsabilidade do parser de manipular a marcação corretamente. - -As classes raramente usadas do analisador como -``ICantBelieveItsBeautifulSoup`` e ``BeautifulSOAP`` foram removidas. -é agora decisão do analisador como manipular marcações ambiguas. - -O método ``prettify()`` agora retorna uma string Unicode, e não bytestring. diff --git a/doc/source/index.rst b/doc/source/index.rst index ac7409f..08063a5 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -3114,6 +3114,27 @@ You can speed up encoding detection significantly by installing the the document, but it can save a lot of memory, and it'll make `searching` the document much faster. +Translating this documentation +============================== + +New translations of the Beautiful Soup documentation are greatly +appreciated. Translations should be licensed under the MIT license, +just like Beautiful Soup and its English documentation are. + +There are two ways of getting your translation into the main code base +and onto the Beautiful Soup website: + +1. Create a branch of the Beautiful Soup repository, add your + translation, and propose a merge with the main branch, the same + as you would do with a proposed change to the source code. +2. Send a message to the Beautiful Soup discussion group with a link to + your translation, or attach your translation to the message. + +Use the Chinese or Brazilian Portuguese translations as your model. In +particular, please translate ``doc/source/index.rst`` file, rather +than the HTML version of the documentation. This makes it possible to +publish the documentation in a variety of formats, not just HTML. + Beautiful Soup 3 ================ -- cgit v1.2.3