Table of Contents
はじめに
BeautifulSoup4の基本的な使い方をまとめてみます。
内容
基本のキ
import requestsfrom bs4 import BeautifulSoup
# htmlの取得res = requests.get('https://www.hoge.com/')
# ローカルに保存with open('res.html', 'w') as file: file.write(res.text)
# htmlパースsoup = BeautifulSoup(res.text, 'html.parser')
# ローカルのhtmlファイルからパースする場合soup = BeautifulSoup(open('res.html'), 'html.parser')selenium と組み合わせて使う
from urllib.parse import urljoinimport re
from bs4 import BeautifulSoupfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options
# driverのオプション設定options = webdriver.ChromeOptions()options.add_argument('--headless')options.add_argument('--no-sandbox')options.add_argument('--disable-dev-shm-usage')driver = webdriver.Chrome('chromedriver',options=options)driver.implicitly_wait(10)
# 基本設定base_url = 'https://www.hoge.com/'driver.get(base_url)html = driver.page_source.encode('utf-8')soup = BeautifulSoup(html, 'html.parser')
# 特定の文字を取得titles = [title.get_text(strip=True) for title in soup.find_all('p', class_='クラス名')]
# リンク先の取得attrs = {'href': re.compile(r'/home.\*')} # /homeで始まるURLだけ抜き出す設定links = [urljoin(base_url, url.get('href')) for url in soup.find_all('a', attrs=attrs)]Scrapyを使う場合
BeautifulSoupはHTMLを解析するライブラリなので、取得・巡回・保存までは自分で書くことになります。ページ数が多い場合や、リンクを辿って収集する場合は、Scrapyのようなフレームワークを使うほうが楽です。
# プロジェクトの作成$ scrapy startproject プロジェクト名
# Spiderの作成$ scrapy genspider Spider名 ドメイン名
# Spiderの実行$ scrapy crawl Spider名
# 対話シェルの起動(セレクタの確認に使う)$ scrapy shellscrapy shell は、実際にページを取得した状態でセレクタを試せる対話環境です。Spiderを書く前にここで抽出条件を固めると、試行錯誤が速くなります。
