4
4

More than 3 years have passed since last update.

BeautifulSoupとSeleniumを組み合わせた自動テストの方法(Python)

Posted at

1.概要

WebページのHTMLに特定のデータを収集するためのタグを埋め込むことがあり、その埋め込んだタグが正しいのか、自動テストを用いてテストを行っていました。

BeautifulSoupを用いたHTMLデータの検索方法

ただ、静的なページであればBeautifulsoupを用いてテストできたのですが、SSL化された画面などのセキュリティが強い画面は、HTMLデータを取得できませんでした。

そのため、BeautifulsoupでHTMLデータを取得できない場合は、Seleniumを用いて対象画面に遷移し、HTMLページを取得することにいたしました。

2.プログラム

以下BeautifulsoupとSeleniumを用いてHTMLデータを取得するプログラムになります

test.py
import time
from selenium import webdriver
from bs4 import BeautifulSoup
import re

#遷移できる画面を起点に、Beautifulsoupで取得できなかった画面まで遷移する
driver.get("test.html")
driver.find_element_by_css_selector("test").click()

#対象画面に遷移できた場合
source = driver.page_source
soup = BeautifulSoup(source,'html.parser')
elems = soup.find_all("script",text=re.compile("test"))

#次の画面に遷移する
driver.find_element_by_css_selector("test").click()

HTMLデータの解析はBeautifulSoupをそのまま使えばよく、

source = driver.page_source
soup = BeautifulSoup(source,'html.parser')

HTMLデータの取得にSeleniumの「.page_source」を使えば問題ありません。

3.まとめ

上記プログラムを必要な画面ごとに作成すれば完成です。また、上記プログラムの場合、起動するとChromeが立ち上がるので、Headlessで起動するのがいいかもしれません。
(Seleniumがちょくちょくエラーで止まるので、あまりHeadlessは使いませんが…)

参考:SeleniumからHeadless Chromeを使ってみた

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4