Python+Docker+Selenium+Chromeでウェブスクレイピングをする part1

Python+Docker+Selenium+Chromeで甘茶の音楽工房ウェブスクレイピングします.本稿では,一通りの設定を実施します.

こちらでも閲覧できますし,まだnoteにしていない記事もあります.
https://www.hamlet-engineer.com/posts/websc_selenium01.html

ただし,jupyter or pythonはローカルです.
作業用BGMとして甘茶の音楽工房の音楽をダウンロードして聞いていました.いい加減面倒臭くなってきたので,ウェブスクレイピングでダウンロードしていきます.

Selenium

本稿では,seleniumでウェブスクレイピングを実施します.以前はrequestsとBeautifulSoupでスクレイピングしていましたが,jsで情報を挿入しているサイトではスクレイピングできないことがありましたので,seleniumを使います.
ちなみに,スクレイピングできなかったサイトは,Fanzaです!!!
DVDのサンプル画像をスクレイピングしようとしていましたwww

Seleniumとは

Selenium は Web ブラウザの操作を自動化するためのフレームワークです。 2004 年に ThoughtWorks 社によって Web アプリケーションの UI テストを自動化する目的で開発されました。 https://selenium.dev/history/ 元々は Web アプリケーションの UI テストや JavaScript のテストの目的で開発されましたが、テスト以外にもタスクの自動化や Web サイトのクローリングなど様々な用途で利用されています。

Docker+Selenium+Chrome

本稿では,Docker上でSeleniumを使います.dockerで使う理由として,chrome driverのversion管理が面倒臭いからです.
有志の方がわかりやすくしてくれているので,がっつりあやかります

docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome:4.0.0-beta-1-prerelease-20201208

Docker+Selenium+Chromeの起動確認

Docker+Selenium+Chromeの起動を確認します.また,ローカル上のChromeを使う際のコードも記載しておきます.

# dockerのselenium
from selenium import webdriver
# Chrome のオプションを設定する
options = webdriver.ChromeOptions()
# Selenium Server に接続する
driver = webdriver.Remote(
   command_executor='http://localhost:4444/wd/hub',
   options=options,
)

# Selenium 経由でブラウザを操作する
url = 'https://amachamusic.chagasi.com/image_ayashii.html'
driver.get(url)
print(driver.current_url)
# 出力:https://amachamusic.chagasi.com/image_ayashii.html
# ローカル上のchromeを使う場合.
# coding: UTF-8
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selene.driver import SeleneDriver
from webdriver_manager.utils import chrome_version
from webdriver_manager.chrome import ChromeDriverManager

# versionに応じたchrome driver のインストール
version = chrome_version()
url = 'http://chromedriver.storage.googleapis.com/LATEST_RELEASE_' + version
response = requests.get(url)
options = Options()
options.add_argument('--headless')

# インストールしたchrome driverでchromeを起動
driver = SeleneDriver.wrap(webdriver.Chrome(
   executable_path=ChromeDriverManager().install(), 
   chrome_options=options))
   
# Selenium 経由でブラウザを操作する
url = 'https://amachamusic.chagasi.com/image_ayashii.html'
driver.get(url)
print(driver.current_url)
# 出力:https://amachamusic.chagasi.com/image_ayashii.html

まとめ

ここまででDocker+Selenium+Chromeの起動を実施しました.おおよその次の記事でSeleniumの操作を検索しながら,必要な工程を実装します.
時間があれば,docker composeまでやってDocker上のjupyterでやりたいです.

有料枠設定にしていますが,youtubeの投げ銭的な物として,お考えください.

参考サイト

10分で理解する Selenium
Docker上でSeleniumとHeadless ChromeとPython3を動かす
Dockerコンテナからseleniumを使ってスクレイピング
Python×SeleniumでWebスクレイピング実践

ここから先は

1字

¥ 100

この記事が気に入ったらサポートをしてみませんか?