LoginSignup
40
43

More than 5 years have passed since last update.

[python, ruby] selenium-webdriverでWebページの内容を取ってくる

Last updated at Posted at 2016-05-12

始めに

RubyとPythonで書いたが、後半Pythonで書くことにしたので、Rubyは簡単な部分のみとなってしまった‥
Ruby部分は追記ということで‥予めご了承ください。

python

インストール

selenium

pip install selenium

chromewebdriver

macだったので

brew install chromedriver

Linuxは以下?(試してないので分からないが…)

sudo apt-get install chromium-browser

参考にしたページ
http://stackoverflow.com/questions/8255929/running-webdriver-chrome-with-selenium

簡単なコード

Googleのホームページにアクセスし、10秒待って閉じるという簡単な例

sample.py
from selenium import webdriver
from time import sleep
browser = webdriver.Chrome()
browser.get('http://google.com')
sleep(10)
browser.close()

ログイン関係

login.py
# id が emailの部分を見つける
mail = browser.find_element_by_id('email')
# id が passの部分を見つける
pass_wd = browser.find_element_by_id('pass')
# emailを入力
mail.send_keys('your@email.com')
# passを入力
pass_wd.send_keys('password')
# 送信
pass_wd.submit()

chromeのNotificationのAllow/Blockを設定

Rubyの場合は放置しても大丈夫だが、Pythonの場合、このPopUpのせいで、プログラムが実行できなくなるので、予めchrome_optionsを設定しておく

変更前
browser = webdriver.Chrome()
変更後
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(chrome_options=chrome_options)

スクロール

スクロールしてページの一番したまでいく

browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

リンクをゲットする

今指定したElementのしたの全てのLink

links = myelement.find_elements_by_xpath(".//a")

今ページ内の全てのリンク

links = myelement.find_elements_by_xpath("//a")

以上のいずれかの情報でLinkをゲットしたら、get_attribute('href')を使ってURLをゲット

urls = [ link.get_attribute('href') for link in links]

参考にしたページ

http://www.takunoko.com/blog/pythonselenium%E3%81%A7twitter%E3%81%AB%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3%E3%81%97%E3%81%A6%E3%81%BF%E3%82%8B/
簡単なログイン

http://selenium-python.readthedocs.io/faq.html
- スクロール
- linkをとる

ruby

インストール

selenium-webdriver gem

gem install selenium-webdriver

chrome driver

chromedriverをダウンロードしてUnzipした後に、
which rubyでrubyのある場所を確認し、そこへ移動

rbenvを使っている場合には、以下のコマンドでOK
mv chromedriver ~/.rbenv/shims

簡単なコード

require "selenium-webdriver"

driver = Selenium::WebDriver.for :chrome
driver.navigate.to "http://google.com"

driver.quit

ログイン関係

## type email
element = driver.find_element(:id, 'email')
element.send_keys 'your@email.com'
# type password
element = driver.find_element(:id, 'pass')
element.send_keys 'password'
# submit the form
element.submit

これで、ログイン後の画面を手に入れることができる。

参考にしたページ

http://shoprev.hatenablog.com/entry/2014/04/14/210529
ChromeDriver設定と簡単なコードの部分で参照

https://gist.github.com/huangzhichong/3284966
詳細昨日に関してはこちらを参照

40
43
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
40
43