0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Selenium 使用方法

Last updated at Posted at 2022-10-06

インストール

$ pip3 install selenium

基本設定

how_to_use_selenium.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys as keys
from selenium.webdriver.support.select import Select

url = 'https://www.google.co.jp/'
driver_path = './chromedriver'

def main():
  driver = webdriver.Chrome(driver_path)
  driver.get(url)
  driver.implicitly_wait(5)

各要素の入力・選択方法

テキストボックス

driver.find_element_by_id('id').send_keys('test')

ボタンのクリック(ラジオボタン、チェックボックス)

## find_element_by_css_selector メソッドの引数に id を指定する
driver.find_element_by_css_selector('#id').click()

セレクトボックス

from selenium.webdriver.support.select import Select

# find_element_by_css_selector メソッドの引数に id を指定する
dropdown = driver.find_element_by_css_selector('#id')
select = Select(dropdown)
select.select_by_index(1)  # 引数に選択したい番号を記入
# select.select_by_index(len(select.options)-3)  # 下の選択肢から数える場合

複数要素取得

driver.find_elements_by_css_selector('.class')

Xpath

driver.find_element_by_xpath('//*[@id="op_num[12]"]')

Dropzone

# https://stackoverflow.com/questions/43382447/python-with-selenium-drag-and-drop-from-file-system-to-webdriver
JS_DROP_FILE = """
    var target = arguments[0],
        offsetX = arguments[1],
        offsetY = arguments[2],
        document = target.ownerDocument || document,
        window = document.defaultView || window;

    var input = document.createElement('INPUT');
    input.type = 'file';
    input.onchange = function () {
      var rect = target.getBoundingClientRect(),
          x = rect.left + (offsetX || (rect.width >> 1)),
          y = rect.top + (offsetY || (rect.height >> 1)),
          dataTransfer = { files: this.files };

      ['dragenter', 'dragover', 'drop'].forEach(function (name) {
        var evt = document.createEvent('MouseEvent');
        evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
        evt.dataTransfer = dataTransfer;
        target.dispatchEvent(evt);
      });

      setTimeout(function () { document.body.removeChild(input); }, 25);
    };
    document.body.appendChild(input);
    return input;
"""

def drag_and_drop_file(drop_target, path):
    driver = drop_target.parent
    file_input = driver.execute_script(JS_DROP_FILE, drop_target, 0, 0)
    try:
        file_input.send_keys(path)
    except:
        print('Error')

dropzone_areas = driver.find_elements_by_css_selector('.dropzone.droparea.dz-clickable')
drag_and_drop_file(dropzone_areas[0], img_path)

おまけ

ある時間に実行開始する方法

import time
import schedule
import argparse
from selenium import webdriver

url = 'https://www.google.co.jp/'
driver_path = './chromedriver'

def main():
  # 引数取得
  parser = argparse.ArgumentParser()
  parser.add_argument('-p')  # パスワード
  args = parser.parse_args()

  driver = webdriver.Chrome(driver_path)
  driver.get(url)
  driver.implicitly_wait(5)

  # at メソッドの引数に実行したい時間を入力
  schedule.every().day.at("00:00:00").do(job)

  while True:
    schedule.run_pending()
    time.sleep(1/1000)

def job():
  driver.refresh()

if __name__ == "__main__":
    main()

会社紹介

株式会社 Mosaica
最先端テクノロジーで社会課題を解決し、持続可能な未来を創造する IT カンパニー。
AI ソリューション、クラウド統合、DX 推進、経営コンサルティングなど包括的なサービスでビジネス変革を支援しています。

詳しくは 公式サイト までお気軽にご相談ください。
公式サイト: https://mosaica.co.jp/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?