20
15

More than 5 years have passed since last update.

【Python】Selenium+Beautifulsoup4を使ってYahoo路線情報を操作する

Last updated at Posted at 2018-08-06

ふと思い立ってPythonをいじったら、思いの外に面白いことができたのでメモ。
初心者向けです。

やりたいこと

下記の操作をすべて自動で行います。
1. ブラウザ(Chrome)を立ち上げる
2. Yahoo路線情報を開く
3. 東京→新宿を入力して検索
4. 一番上に出てきた結果の出発時刻と到着時刻をターミナルに表示する
5. ブラウザを閉じる

python3系とpip, Homebrewが使える状態を前提とします。mac使っています。

ライブラリのインストール

pipとbrewを使ってbeautifulsoup4とSelenium、ChromeDriverをインストール

#BeautifulSoup4とSeleniumのインストール
$ pip install beautifulsoup4
$ pip install selenium
#Selenium ChromeDriverのインストール
$ brew install chromedriver

Yahoo路線情報を操作するプログラムを書く

selenium-test-yahootransit.py
# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from bs4 import BeautifulSoup

start = "東京" #出発駅
end = "新宿" #到着駅

print(start + "駅から" + end + "駅への直近の電車を調べます...")

#ブラウザを開く
driver = webdriver.Chrome()

#Yahoo路線情報を開く
driver.get("https://transit.yahoo.co.jp/")

#出発駅と到着駅の入力
driver.find_element_by_id("sfrom").send_keys(start)
driver.find_element_by_id("sto").send_keys(end)

#検索ボタンをクリックする
driver.find_element_by_id("searchModuleSubmit").click()

#検索結果のページのHTMLをBeautifulSoupに流し込む
soup = BeautifulSoup(driver.page_source, "html5lib")

#時間が書かれた部分をCSSセレクタで指定し、テキストを抜き出す
time = soup.select(".routeSummary li.time")[0].select("span")[0].text

#結果を表示する
print("結果:" + time + "です。")

#ブラウザを閉じる
driver.close()

実際の動作

selenium-test-yahootransit.gif

20
15
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
20
15