LoginSignup
1
2

More than 5 years have passed since last update.

コミュニティサイクルの利用履歴をスクレイピング v2

Posted at

はじめに

2016年5月にコミュニティサイクルの利用履歴をスクレイピングという記事を書きました。
あれから1年以上が経過し、そのときのスクリプトでは動作しなくなってしまいました。
そこで現在でも動作するようにしようと思い書き始めました。

やってみたこと

今回もまずは、Python3 + BeautifulSoup4 + Selenium + Firefox で動作させます。
※最近のFirefoxをSeleniumと連携させるにはgeckodriverというのが必要です。

docomo-cycle2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import urllib.request
from bs4 import BeautifulSoup
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import csv

MEMBERID = "(自分のユーザID)"
PASSWORD = "(自分のパスワード)"

driver = webdriver.Firefox()
driver.get("https://tcc.docomo-cycle.jp/cycle/TYO/cs_web_main.php?AreaID=2")

mid = driver.find_element_by_name('MemberID')
mid.send_keys(MEMBERID)
password = driver.find_element_by_name('Password')
password.send_keys(PASSWORD)
password.send_keys(Keys.RETURN)

obj1 = WebDriverWait(driver,5).until(
    EC.presence_of_element_located((By.XPATH, "//*[@id='pc_bill']")))
obj1.click()

time.sleep(3)

data = driver.page_source.encode('utf-8')
soup = BeautifulSoup(data, "html.parser")

table = soup.findAll("table",{"class":"rnt_ref_table"})[0]
rows = table.findAll("tr")

csvFile = open("docomo-cycle2.csv", 'wt', newline='', encoding='utf-8')
writer = csv.writer(csvFile)
try:
  for row in rows:
    csvRow = []
    for cell in row.findAll(['td', 'th']):
      csvRow.append(cell.get_text().replace('\n',''))
    writer.writerow(csvRow)
finally:
  csvFile.close()


driver.close()

上記スクリプトを動かすと、docomo-cycle2.csvというファイルに利用履歴が出力されます。
Mac環境とWindows環境で動作確認済みです。

今後のこと

実は、Headless Chrome向けのサンプルプログラムを作ろうとしたところ、どこで問題が発生しているのかが、Headlessだとわかりにくいため、Firefoxを使って人間の目で確認しつつデバッグしようと思い、この記事を書き始めました。
やっとこれでデバッグできたので、次はこのサンプルプログラムをHeadless Chromeで動かす場合の記事を書きたいと思います。

1
2
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
1
2