Pythonのインストール
Seleniumとchromedriver-binaryのインストール
python -m pip install --upgrade pip pip install selenium pip install chromedriver-binary
最後の行のchromedriver-binaryは、Chromeを操作するためのドライバー。本体はchromedriver.exeという実行ファイルで、これを介してブラウザを操作します。
ただし、このchromedriver.exeは、操作するブラウザのバージョンに依存します。
これが色々と厄介で、例えば会社のPCは古いバージョンのChromeが入っている、それに合わせて開発したら、自動バージョンアップされて動かなくなる、という事態がまあ頻繁に起きます。
バージョンを指定してインストールするには、まずPCに入っているChromeのバージョンを確認します。
右上の「…」ボタン → ヘルプ → Google Chromeについて をクリックすると、以下の画面が出てきます。
「If you are using Chrome version 85, please download ChromeDriver 85.0.4183.87」←これが、使用すべきchromedriverのバージョンです。
バージョン指定してインストールするコマンドは↓
pip install chromedriver-binary==85.0.4183.87
この他に、chromedriver.exeをダウンロードし、パスを直接指定する方法もありますが、どちらにしてもChromeのメジャーバージョンアップ時にはメンテが必要です。仕事で使っていると、朝から「使えないよ!!」の声がブワッと挙がり…
VSCodeのインストール(任意)
Visual Studio Code(VSCode)とは、Microsoft社製のテキストエディタ・総合開発ツールです。エディタと言うと、ちょっと昔は個人作成のフリーソフトが流行りでしたが、Google(Atom)とMicrosoft(VSCode)の2大巨頭が進出し、VSCodeがスタンダードになりつつあります。Atomは重くて不安定だったけど、今はどうだろう?
もちろん、好みのテキストエディタでコードを書き、コマンドプロンプト(今はPowerShell/Terminalが推奨されているが…)でpythonを実行しても良いのですが、一つの画面で出来たら作業がはかどります。
インストールしたら、左のエクステンションメニュー(ブロックが積まれたようなアイコン)から、検索ボックスに「Python」と入力し、Microsoft謹製ツールをインストールします。
これで、Pythonコードのハイライトや、入力支援、プログラム実行機能が使用できます。
Selenium基本動作のクラスを作成
これで準備が整いました。あとは、コードを書いて実行するだけです。
その前に、Webページに対する「クリック」「文字入力」等の基本操作をまとめてクラス化し、別ファイルにして管理するとメンテナンスが楽になります。
SeleniumFunctions.py
import sys
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
class SeleniumFunctions:
def __init__(self, default_wait=30):
self.default_wait = default_wait
def open_chrome(self, url, is_headless, page_timeout=60):
options = Options()
if is_headless:
options.add_argument('--headless')
self.driver = webdriver.Chrome(options=options)
self.driver.set_page_load_timeout(page_timeout)
try:
self.driver.get(url)
except:
print('Error or Timeout')
def close_chrome(self):
self.driver.quit()
def click(self, xpath):
try:
WebDriverWait(self.driver, self.default_wait).until(EC.visibility_of_element_located((By.XPATH, xpath)))
WebDriverWait(self.driver, self.default_wait).until(EC.element_to_be_clickable((By.XPATH, xpath)))
element = self.driver.find_element_by_xpath(xpath)
element.click()
print(f'SUCCESS : {xpath} clicked')
except:
print(f'ERROR : {xpath} could not click. {str(sys.exc_info()[0])}')
def input(self, xpath, input_str):
try:
WebDriverWait(self.driver, self.default_wait).until(EC.visibility_of_element_located((By.XPATH, xpath)))
element =self.driver.find_element_by_xpath(xpath)
element.send_keys(input_str)
print(f'SUCCESS : input {input_str} to {xpath}')
except:
print(f'ERROR : {xpath} could not input. {str(sys.exc_info()[0])}')
def select(self, xpath, select_val):
try:
WebDriverWait(self.driver, self.default_wait).until(EC.visibility_of_element_located((By.XPATH, xpath)))
element = self.driver.find_element_by_xpath(xpath)
Select(element).select_by_value(select_val)
print(f'SUCCESS : select {select_val} to {xpath}')
except:
print(f'ERROR : {xpath} could not select. {str(sys.exc_info()[0])}')
def get_text(self, xpath):
try:
WebDriverWait(self.driver, self.default_wait).until(EC.visibility_of_element_located((By.XPATH, xpath)))
element = self.driver.find_element_by_xpath(xpath)
print(f'SUCCESS : get text from {xpath}')
return element.text
except:
print(f'ERROR : {xpath} could not get text. {str(sys.exc_info()[0])}')
関数の解説
XPATHによる指定
LINEモバイルマイページにログインし、月額料金を取得するPythonプログラム
先のSeleniumFunctions.pyは、C:\myCodes\Selenium配下に置いて、sys.path.appendでフォルダを追加した後にimportします。これで本体はだいぶスッキリしますね。import sys
import time
import re
from os import path
sys.path.append('C:/myCodes/Selenium')
from SeleniumFunctions import SeleniumFunctions
ini_file = path.join(path.dirname(__file__), 'line_accounts.ini')
with open(ini_file, 'r', encoding='utf-8') as f:
iniLines = f.readlines()
result_text = ''
for iniLine in iniLines:
currentId = iniLine.strip().split(",")[0]
currentPass = iniLine.strip().split(",")[1]
sf = SeleniumFunctions()
sf.open_chrome('https://mobile.line.me/mypage/bill/', True)
sf.input('//input[@name="loginAccount"]', currentId)
sf.input('//input[@name="loginPassword"]', currentPass)
sf.click('//input[@id="FnNextBtn"]')
result_text += currentId + '\n' + sf.get_text('//div[@data-index="1"]') + '\n'
sf.close_chrome()
print(result_text)
output_file = path.join(path.dirname(__file__), re.search(r'\d+年\d+月', result_text).group() + '_LINE月額料金.txt')
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(result_text)
同フォルダにline_accounts.iniを置き、ここに






0 件のコメント:
コメントを投稿