技術雑記帳兼日記帳

AWS、Python、Terraformの使い方をコッソリ

python スクレイピング その5

はじめに

今回は短めにヘッドレスモードを試してみる。

準備

  • sele_headless.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time

url = 'https://srad.jp/'
keyword = 'Linux'

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options, executable_path="chromedriverのパス")
driver.get(url)

search = driver.find_element_by_name("fhfilter")
search.send_keys(keyword)
search.submit()

soup = BeautifulSoup(driver.page_source, "html.parser")
results = soup.find_all("h2", attrs={"class": "story"})

for i, result in enumerate(results):
    tag = result.find("a")
    print("%d: %s : %s" % (i + 1, tag.get_text(), "https:"+tag["href"]))

driver.quit()
  • 実行方法と結果
$ python sele_headless.py
1: Microsoft、eBPFをWindows上で利用可能にする計画 : https://opensource.srad.jp/story/21/05/11/1940206/
2: Windows 10 Insider Preview ビルド21376、WSLのLinux GUIアプリサポートで発生していた問題を解決 : https://linux.srad.jp/story/21/05/08/0455217/
3: Vine Linuxの現状は?(追記: リリース版終了が宣言される) : https://linux.srad.jp/story/21/05/04/0459248/
4: Windows 10 Insider PreviewのLinux GUIアプリ実行サポート、現時点ではHaswell世代以降のCPUが必要 : https://linux.srad.jp/story/21/04/29/0430220/
5: ミネソタ大研究者、研究のためとしてLinuxカーネルに意図的に脆弱性コードをコミット : https://linux.srad.jp/story/21/04/25/1954223/
6: M1 Mac正式対応のOS仮想化ソフト「Parallels Desktop 16.5」が公開 : https://linux.srad.jp/story/21/04/19/0129216/
7: SCO Linux FUDは滅びぬ、何度でも蘇るさ! : https://linux.srad.jp/story/21/04/04/1616223/
8: FSF運営チーム、執行役員をはじめ3名が辞任へ : https://opensource.srad.jp/story/21/04/03/0837231/
9: Linux Foundation、Linux 30周年記念ロゴ画像を公開 : https://linux.srad.jp/story/21/03/21/058252/
10: 7-Zip 20.01 alpha、Linuxに対応 : https://linux.srad.jp/story/21/03/16/1622251/
11: 火星の空飛ぶLinux : https://linux.srad.jp/story/21/03/11/1655218/
12: Linux 5.12 rc2、重大なバグ修正のため予定より数日早くリリース : https://linux.srad.jp/story/21/03/07/0039241/
13: Linus Torvalds、6日間の電源喪失を切り抜ける : https://linux.srad.jp/story/21/03/02/1653247/
14: アップデート適用が進まないLinux Mint、より多くのユーザーに迅速なアップデート適用を実行してもらうための改善計画 : https://linux.srad.jp/story/21/02/28/1940228/
  • 簡単な解説

options.add_argument('--headless')を追加することで、Chromeが画面に表示されずにスクレイピングができる。

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options, executable_path="chromedriverのパス")

まとめ

バックグラウンドでスクレイピングできるのは便利。
GUIのないテストシステムとかで使えそう。