インストール
$ 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()