LoginSignup
2
0

More than 3 years have passed since last update.

【Python】WEBサイトへ自動ログイン

Posted at

Pixivへ自動ログインするプログラムの制作

WEBスクレイピングをやりたくてPythonの勉強をはじめました。
初心者なのでお手柔らかにお願いします。

動作環境

  • macOS Catalina-ver10.15.7
  • Python 3.8.5
  • JupyterLab
  • ChromeDriver 89.0.4389.23

JupyterLabのNotebookで動作を確認しながらコードをかきます。

使用ライブラリ:selenium、pandas

ターミナルよりpipでseleniumをインストール。
pandasはcondaで既にインストール済みのものを使用。

code0

#!/usr/bin/env python
# coding: utf-8

from selenium import webdriver
import time
import pandas as pd

1、Chromeを起動してログインページへ移動

homebrewというパッケージマネージャを使用して、ChromeDriverをインストール。
これでGoogle Chromeで自動操作ができるようになる。

code1

USER = "AAA"
PASS = "AAA"

# GoogleChromeを起動
browser = webdriver.Chrome()
browser.implicitly_wait(3)

# ログインページするサイトへアクセス
url_login = "https://accounts.pixiv.net/login"
browser.get(url_login)
time.sleep(2)
print("ログインページにアクセスしました")

2、ログイン情報の入力

IDやPASS情報を入力するボックスにユニークなHTMLタグがついていないため、
デベロッパーツールからXPathを取得。
テキストボックスを空にする為に一応 element.clear() を入れておく。
情報が入ったので、ログインボタンまで押してもらう。

これで自動ログインが完了:grinning:
code2

# ログイン情報を入力
element = browser.find_element_by_xpath('//*[@id="LoginComponent"]/form/div[1]/div[1]/input');
element.clear()
element.send_keys(USER)
element = browser.find_element_by_xpath('//*[@id="LoginComponent"]/form/div[1]/div[2]/input');
element.clear()
element.send_keys(PASS)
print("フォームを送信")

# ログインボタンを押下
browser_from = browser.find_element_by_xpath('//*[@id="LoginComponent"]/form/button')
time.sleep(3)
browser_from.click()
print("ログインボタンを押しました")

参考

キノコードさんのWEBスクレイピング講座を元に作成しました。

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