BeautifulSoupモジュール 編集

BeautifulSoupは、Pythonのサードパーティライブラリであり、HTMLやXMLのパースやスクレイピングに使用される機能を提供します。

HTML/XMLのパース 編集

BeautifulSoupを使用すると、HTMLやXMLのドキュメントをパースして要素の階層構造を把握することができます。

パースの例 編集

from bs4 import BeautifulSoup

# HTMLをパース
html = '<html><body><h1>Hello, BeautifulSoup!</h1></body></html>'
soup = BeautifulSoup(html, 'html.parser')

# 要素の取得とテキスト表示
heading = soup.h1
print(heading.text)

要素の検索 編集

BeautifulSoupを使用すると、特定の要素を検索することができます。

要素の検索の例 編集

from bs4 import BeautifulSoup

# HTMLをパース
html = '<html><body><h1>Hello, BeautifulSoup!</h1><p>Example paragraph</p></body></html>'
soup = BeautifulSoup(html, 'html.parser')

# h1要素の取得とテキスト表示
heading = soup.find('h1')
print(heading.text)

# p要素の取得とテキスト表示
paragraph = soup.find('p')
print(paragraph.text)

要素の属性やテキストの取得 編集

BeautifulSoupを使用すると、要素の属性やテキストを取得することができます。

属性やテキストの取得の例 編集

from bs4 import BeautifulSoup

# HTMLをパース
html = '<html><body><a href="https://www.example.com">Example Link</a></body></html>'
soup = BeautifulSoup(html, 'html.parser')

# a要素のhref属性の取得
link = soup.find('a')
href = link['href']
print(href)

# a要素のテキストの取得
text = link.text
print(text)

要素の操作 編集

BeautifulSoupを使用すると、要素の作成や削除、属性の追加や変更など、要素の操作が可能です。

要素の操作の例 編集

from bs4 import BeautifulSoup

# HTMLをパース
html = '<html><body><p>Example paragraph</p></body></html>'
soup = BeautifulSoup(html, 'html.parser')

# 新しい要素の作成と追加
new_element = soup.new_tag('h2')
new_element.string = 'New Heading'
soup.body.append(new_element)

# 要素の削除
paragraph = soup.find('p')
paragraph.decompose()

# 変更後のHTMLの表示
print(soup.prettify())

注意 編集

これらはBeautifulSoupモジュールの基本的な機能の一部です。詳細な情報や他の機能については、公式のBeautifulSoupドキュメントを参照してください。