Beautiful-soup-modifying-the-tree

提供:Dev Guides
移動先:案内検索

美しいスープ-ツリーを変更する

BeautifulSoupの重要な側面の1つは、解析ツリーを検索することです。これにより、要件に応じてWebドキュメントに変更を加えることができます。 .name、.string、.append()メソッドなどの属性を使用して、タグのプロパティを変更できます。 .new_string()および.new_tag()メソッドを使用して、既存のタグに新しいタグと文字列を追加できます。 .insert()、. insert_before()、. insert_after()など、HTMLまたはXMLドキュメントにさまざまな変更を加える他のメソッドもあります。

タグ名と属性の変更

スープを作成したら、タグの名前変更、属性の変更、新しい属性の追加、属性の削除などの変更を簡単に行うことができます。

>>> soup = BeautifulSoup('<b class="bolder">Very Bold</b>')
>>> tag = soup.b

新しい属性の変更と追加は次のとおりです-

>>> tag.name = 'Blockquote'
>>> tag['class'] = 'Bolder'
>>> tag['id'] = 1.1
>>> tag
<Blockquote class="Bolder" id="1.1">Very Bold</Blockquote>

属性の削除は次のとおりです-

>>> del tag['class']
>>> tag
<Blockquote id="1.1">Very Bold</Blockquote>
>>> del tag['id']
>>> tag
<Blockquote>Very Bold</Blockquote>

.stringの変更

タグの.string属性を簡単に変更できます-

>>> markup = '<a href="https://www.finddevguides.com/index">Must for every <i>Learner>/i<</a>'
>>> Bsoup = BeautifulSoup(markup)
>>> tag = Bsoup.a
>>> tag.string = "My Favourite spot."
>>> tag
<a href="https://www.finddevguides.com/index">My Favourite spot.</a>

上記から、タグに他のタグが含まれているかどうかを確認できます。タグとそのすべてのコンテンツが新しいデータに置き換えられます。

append()

既存のタグに新しいデータ/コンテンツを追加するには、tag.append()メソッドを使用します。 Pythonリストのappend()メソッドとよく似ています。

>>> markup = '<a href="https://www.finddevguides.com/index">Must for every <i>Learner</i></a>'
>>> Bsoup = BeautifulSoup(markup)
>>> Bsoup.a.append(" Really Liked it")
>>> Bsoup
<html><body><a href="https://www.finddevguides.com/index">Must for every <i>Learner</i> Really Liked it</a></body></html>
>>> Bsoup.a.contents
['Must for every ', <i>Learner</i>, ' Really Liked it']

NavigableString()および.new_tag()

ドキュメントに文字列を追加する場合は、append()を使用するか、NavigableString()コンストラクタを使用して簡単に行うことができます-

>>> soup = BeautifulSoup("<b></b>")
>>> tag = soup.b
>>> tag.append("Start")
>>>
>>> new_string = NavigableString(" Your")
>>> tag.append(new_string)
>>> tag
<b>Start Your</b>
>>> tag.contents
['Start', ' Your']
  • 注意:*次のように、NavigableString()関数にアクセス中に名前エラーが見つかった場合

NameError:名前「NavigableString」が定義されていません

ちょうどbs4パッケージからNavigableStringディレクトリをインポートします-

>>> from bs4 import NavigableString

上記のエラーを解決できます。

既存のタグにコメントを追加したり、NavigableStringの他のサブクラスを追加したりできます。コンストラクタを呼び出すだけです。

>>> from bs4 import Comment
>>> adding_comment = Comment("Always Learn something Good!")
>>> tag.append(adding_comment)
>>> tag
<b>Start Your<!--Always Learn something Good!--></b>
>>> tag.contents
['Start', ' Your', 'Always Learn something Good!']

新しいタグ全体を追加する(既存のタグに追加しない)には、Beautifulsoup組み込みメソッドBeautifulSoup.new_tag()を使用します。

>>> soup = BeautifulSoup("<b></b>")
>>> Otag = soup.b
>>>
>>> Newtag = soup.new_tag("a", href="https://www.finddevguides.com")
>>> Otag.append(Newtag)
>>> Otag
<b><a href="https://www.finddevguides.com"></a></b>

最初の引数であるタグ名のみが必須です。

インサート()

Pythonリストの.insert()メソッドと同様に、tag.insert()は新しい要素を挿入しますが、tag.append()とは異なり、新しい要素は必ずしも親のコンテンツの最後に配置されるわけではありません。 新しい要素は任意の位置に追加できます。

>>> markup = '<a href="https://www.djangoproject.com/community/">Django Official website <i>Huge Community base</i></a>'
>>> soup = BeautifulSoup(markup)
>>> tag = soup.a
>>>
>>> tag.insert(1, "Love this framework ")
>>> tag
<a href="https://www.djangoproject.com/community/">Django Official website Love this framework <i>Huge Community base</i></a>
>>> tag.contents
['Django Official website ', 'Love this framework ', <i>Huge Community base</i
>]
>>>

insert_before()およびinsert_after()

解析ツリーの何かの直前にタグまたは文字列を挿入するには、insert_before()を使用します-

>>> soup = BeautifulSoup("Brave")
>>> tag = soup.new_tag("i")
>>> tag.string = "Be"
>>>
>>> soup.b.string.insert_before(tag)
>>> soup.b
<b><i>Be</i>Brave</b>

同様に、解析ツリー内の何かの直後にタグまたは文字列を挿入するには、insert_after()を使用します。

>>> soup.b.i.insert_after(soup.new_string(" Always "))
>>> soup.b
<b><i>Be</i> Always Brave</b>
>>> soup.b.contents
[<i>Be</i>, ' Always ', 'Brave']

clear()

タグの内容を削除するには、tag.clear()を使用します-

>>> markup = '<a href="https://www.finddevguides.com/index">For <i>technical & Non-technical&lr;/i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> tag = soup.a
>>> tag
<a href="https://www.finddevguides.com/index">For <i>technical & Non-technical</i> Contents</a>
>>>
>>> tag.clear()
>>> tag
<a href="https://www.finddevguides.com/index"></a>

エキス()

ツリーからタグまたは文字列を削除するには、PageElement.extract()を使用します。

>>> markup = '<a href="https://www.finddevguides.com/index">For <i&gr;technical & Non-technical</i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>>
>>> i_tag = soup.i.extract()
>>>
>>> a_tag
<a href="https://www.finddevguides.com/index">For Contents</a>
>>>
>>> i_tag
<i>technical & Non-technical</i>
>>>
>>> print(i_tag.parent)
None

decompose()

tag.decompose()は、ツリーからタグを削除し、その内容をすべて削除します。

>>> markup = '<a href="https://www.finddevguides.com/index">For <i>technical & Non-technical</i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>> a_tag
<a href="https://www.finddevguides.com/index">For <i>technical & Non-technical</i> Contents</a>
>>>
>>> soup.i.decompose()
>>> a_tag
<a href="https://www.finddevguides.com/index">For Contents</a>
>>>

と置換する()

名前が示すように、pageElement.replace_with()関数は、ツリー内の古いタグまたは文字列を新しいタグまたは文字列に置き換えます-

>>> markup = '<a href="https://www.finddevguides.com/index">Complete Python <i>Material</i></a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>>
>>> new_tag = soup.new_tag("Official_site")
>>> new_tag.string = "https://www.python.org/"
>>> a_tag.i.replace_with(new_tag)
<i>Material</i>
>>>
>>> a_tag
<a href="https://www.finddevguides.com/index">Complete Python <Official_site>https://www.python.org/</Official_site></a>

上記の出力では、replace_with()が置換されたタグまたは文字列(この例では「Material」のように)を返すことに気付いたので、それを調べたり、ツリーの別の部分に追加したりできます。

ラップ()

pageElement.wrap()は、指定したタグで要素を囲み、新しいラッパーを返します-

>>> soup = BeautifulSoup("<p>finddevguides.com</p>")
>>> soup.p.string.wrap(soup.new_tag("b"))
<b>finddevguides.com</b>
>>>
>>> soup.p.wrap(soup.new_tag("Div"))
<Div><p><b>finddevguides.com</b></p></Div>

unwrap()

tag.unwrap()はwrap()の反対で、タグをそのタグ内の任意のものに置き換えます。

>>> soup = BeautifulSoup('<a href="https://www.finddevguides.com/">I liked <i>finddevguides</i></a>')
>>> a_tag = soup.a
>>>
>>> a_tag.i.unwrap()
<i></i>
>>> a_tag
<a href="https://www.finddevguides.com/">I liked finddevguides</a>

上記から、replace_with()と同様に、unwrap()は置換されたタグを返すことがわかりました。

以下は、それをよりよく理解するためのunwrap()のもう1つの例です-

>>> soup = BeautifulSoup("<p>I <strong>AM</strong> a <i>text</i>.</p>")
>>> soup.i.unwrap()
<i></i>
>>> soup
<html><body><p>I <strong>AM</strong> a text.</p></body></html>

unwrap()はマークアップを取り除くのに適しています。