◆ Selenium はイヤ
◆ pychrome 使ってみた

ネットみてたら Python を使って Chrome を動かしてスクレイピングするという記事がありました
どうやってやるんだろう と思って読んでみたら

Selenium

あぁ それね……

Selenium って重いし入れるの面倒だし Java だしと 個人的には嫌いです
ウェブページの E2E テストだとほぼ Selenium なんですよねー
それが何年か前に調べたときに Selenium なしで (自前で WebDriver を書いてるみたい) できるツールを見つけたときには感動したものです
ただ 残念なことにメンテされず放置されていて ブラウザの変更に対応できず動かないようになっていました
最近は他に Selenium なしのテストツールなんかでてるんだっけ?

話を戻して Chrome には CDP とかあるんだし Selenium なしでも Python でできるんじゃないの?と思って調べてみると いろいろな言語のライブラリがありました
https://github.com/ChromeDevTools/awesome-chrome-devtools

Python は 3 種類ありました
PyChromeDevTools
chromewhip
pychrome

今回はとりあえず一番スターが多くて Readme で使い方が一番わかりやすかった pychrome を使ってみました
CDP は Chrome をリモート操作するためのもので ポートをリッスンしてる Chrome に接続してから命令を送るものです
Chrome を起動したり終了したりという機能はないです
なので Chrome の起動も Python で行います
環境は Windows なので start コマンドを実行して headless モードで remote debug のポートを 9222 にして起動します

import subprocess
import pychrome
import json

subprocess.run('start "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --headless --disable-gpu --remote-debugging-port=9222', shell=True)

browser = pychrome.Browser(url="http://127.0.0.1:9222")
tab = browser.new_tab()
tab.start()
tab.Network.enable()
tab.Page.navigate(url="https://github.com/fate0/pychrome", _timeout=5)
tab.wait(5)
result = tab.Runtime.evaluate(expression="""
JSON.stringify([...document.links].map(e => e.href))
""")
print(json.loads(result["result"]["value"]))

browser.close_tab(tab)

ブラウザに接続後 新しいタブを開いて pychrome の github のページを開き ページ内のリンク一覧を取得します
ブラウザ上で動かす部分のプログラムは JavaScript です
JSON 化したデータを返して Python で JSON をパースするのが受け渡ししやすそうだったので JSON にしてます

出力はこういう感じです
リンクが並んでるだけで長いので中略してます

['https://github.com/fate0/pychrome#start-of-content',
'https://github.com/',
'https://github.com/features',
'https://github.com/features/code-review/',
'https://github.com/features/project-management/',
'https://github.com/features/integrations',
'https://github.com/features/actions',
'https://github.com/features#team-management',
(略)
'https://training.github.com/',
'https://github.blog/',
'https://github.com/about',
'https://github.com/fate0/pychrome',
'https://github.com/fate0/pychrome']

調べてみたら puppeteer (CDP を使って便利にブラウザ操作できるようにしたライブラリ) の Python 版もあるみたいなのでそっちを使ったほうがいいかもですね
pyppeteer