BeautifulSoupでHTMLから要素を抽出
BeautifulSoupのみを使ってHTMLから要素を抽出するサンプルです
準備
BeautifulSoupをインポート
「html 」にhtmlコードを代入
from bs4 import BeautifulSoup
html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Smple Document</title>
</head>
<body>
<h1>サンプルHTML</h1>
<div class="sample_list">
<h2>サンプルリスト</h2>
<ul>
<li>
<h3>リンク1</h3>
<a href="https:urlサンプル1"></a>
</li>
<li>
<h3>リンク2</h3>
<a href="https:urlサンプル2"></a>
</li>
<li>
<h3>リンク3</h3>
<a href="https:urlサンプル3"></a>
</li>
</ul>
</div>
</body>
</html>
'''
抽出例いろいろ
h1を取得
soup = BeautifulSoup(html, 'html.parser')
print(soup.h1)
結果 ↓
<h1>サンプルHTML</h1>
h1をテキストで取得
soup = BeautifulSoup(html, 'html.parser')
print(soup.h1.text)
結果 ↓
サンプルHTML
html内のリンクをすべて取得
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
結果 ↓
https:urlサンプル1
https:urlサンプル2
https:urlサンプル3
div内の<li>のh3タイトルとリンクを取得
soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div')
for li in div.find_all('li'):
print(li.find('h3').text)
for link in li.find_all('a'):
print(link.get('href'))
結果 ↓
リンク1
https:urlサンプル1
リンク2
https:urlサンプル2
リンク3
https:urlサンプル3