LoginSignup
8
7

More than 5 years have passed since last update.

Seleniumでログインを含めてWebスクレイピングしてみた

Posted at

この記事は

Webでログインが必要なスクレイピングを簡単に紹介する。

環境

Centos 7.5.1804
ChromeDriver 2.35
Python 3.6.3

環境構築

ChromeDriverのインストールをよくまとめたところ
https://qiita.com/yuki-k/items/716bd05f087fc0f835bf

python seleniumインストール
https://selenium-python.readthedocs.io/installation.html

使用例

facebookにログインして鐘アイコンのHTMLを取得する。
login.png

facebookログインに使うHTML elementの属性を確認

ログインに使うEmailのinput element(name="email")
email.png

暗証番号に使うinput element(name="pass")
pass.png

ログインを実行に使うlabel element(id="loginbutton")
loginBtn.png

python全体コード

# coding: utf-8

import sys

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

if __name__ == "__main__":
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(executable_path='/chromedriverが/ある/パスを/書く', chrome_options=chrome_options)

    print('ログイン中')
    driver.get('https://www.facebook.com/')
    driver.find_element_by_name('email').send_keys('facebookログインemailを書く')
    driver.find_element_by_name('pass').send_keys('暗証番号を書く')
    driver.find_element_by_id('loginbutton').click()
    html = driver.find_element_by_name('notifications').get_attribute('outerHTML')
    print(html)

コード説明

facebookログインページにアクセス

driver.get('https://www.facebook.com/')

HTMLのname属性がemailであるところに使用するメールをセットする

driver.find_element_by_name('email').send_keys('facebookログインemailを書く')

HTMLのname属性がpassであるところにメールの暗証番号をセットする

    driver.find_element_by_name('pass').send_keys('暗証番号を書く')

HTMLのid属性がloginbuttonであるところをclickする

driver.find_element_by_id('loginbutton').click()

HTMLのname属性がnotificationsであるところのHTMLを取得

html = driver.find_element_by_name('notifications').get_attribute('outerHTML')
print(html)

HTMLを取得したところのprint(html)の結果
login_console.png

以上

8
7
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
8
7