(126) Hyper-V仮想マシン上のヘッドレスUbuntu22でSeleniumを動かす。

投稿者: | 2025年4月14日

72 views

1. やりたいこと

Windows11の Hyper-V上で Ubuntu22仮想マシンを動かしている。
普段は Windows11から Puttyで ssh接続し、CUIで操作している。

この環境で Python + Seleniumを使って Webスクレイピングを実行したい。

2. やってみる

1) Web Browserをインストールする。

Webブラウザには Google Chromeを使用する。

$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
$ sudo apt install ./google-chrome-stable_current_amd64.deb -y

インストールできたことを確認する。

$ google-chrome --version
Google Chrome 135.0.7049.84

2) Web Driverをインストールする。

Webドライバとは、Webブラウザと外部プログラムを接続するための仲介プログラムだ。
今回は Webブラウザに Google Chromeを使うので、これに対応した Google社製の Webドライバを使う。

上で Chromeのバージョンを確認し、下記サイトでこれに対応する Webドライバを選択する。
https://googlechromelabs.github.io/chrome-for-testing/

今回は、Version: 135.0.7049.84 chromedriver linux64用をインストールする。

$ wget https://storage.googleapis.com/chrome-for-testing-public/135.0.7049.84/linux64/chromedriver-linux64.zip
$ unzip chromedriver_linux64.zip

こちらも念のためにバージョンを確認しておく。

$ ./chromedriver-linux64/chromedriver --version
ChromeDriver 135.0.7049.84 (6c019e56001911b3fd467e03bf68c435924d62f4-refs/branch-heads/7049@{#1778})

3) Python Seleniumをインストールする。

$ pip install selenium

4) Python + Seleniumで Webスクレイピングしてみる!

Pythonを起動する。

$ python

Pythonシェルでプログラムを実行する。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# Headless Chrome用オプション
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")  # Chrome 109以降で推奨
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")

# Webドライバーサービス
service = Service("./chromedriver-linux64/chromedriver")
driver = webdriver.Chrome(service=service, options=options)

# 気象庁のヘッドラインを取得する。
driver.get("https://www.jma.go.jp/jma/index.html")
time.sleep(5)
div_news = driver.find_element(By.ID, "news")
headlines = div_news.find_elements(By.TAG_NAME, "a")
for title in headlines :
    print(title.text)

できた。

ひまわり9号の保守作業に伴う観測休止の予定について
令和7年3月の地震活動及び火山活動について
南海トラフ地震関連解説情報について -最近の南海トラフ周辺の地殻活動-
霧島山(新燃岳)の警戒が必要な範囲を概ね3kmに縮小
霧島山(新燃岳)の噴火警戒レベルを3へ引上げ
特殊切手「気象業務150周年」が令和7年5月28日に発行されます。
石垣島の日最高気温及び日最低気温の過去データについて

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です