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