Skip to content

Instantly share code, notes, and snippets.

@eggplants
Last active July 13, 2021 18:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eggplants/7f0288468e51e390f94801762bf7a9c8 to your computer and use it in GitHub Desktop.
Save eggplants/7f0288468e51e390f94801762bf7a9c8 to your computer and use it in GitHub Desktop.
sudo apt install chromium-browser chromium-chromedriver python3-selenium -y && sudo apt update && sudo apt -f install -y && pip install selenium
# ##################################################### #
# SeleniumをPythonでさくっと動かしたいときの基本形はこんな感じ #
# (以下はChrome を動かしたいときを想定) #
# ##################################################### #
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
o = Options()
##################
# ...options... #
##################
d = webdriver.Chrome(options=o)
###################
# ...processes... #
###################
d.quit() # ドライバ+画面を終了
# 画面のみ:d.close()
o = Options()
o.add_argument(argument)
# ブラウザの起動オプションを設定する
# Chromeの引数:http://chrome.half-moon.org/43.html
# よく使う引数として、
# --headless 画面なし起動
# --disable-gpu :
# --no-sandbox : Chrome独自の保護機能が無効の状態で起動, タブごとのプロセス独立(サンドボックス状態)を無効にする
# --window-size=1024,768
# --lang= とか…
o.add_encoded_extension(extension)
# Base64でエンコードされた拡張のデータを追加
# 引数はその文字列
o.add_experimental_option(name, value)
# ブラウザの実験的なオプションの追加
# nameにオプション名、valueにオプション引数
o.add_extension(extension)
# 拡張機能のパスを追加
# Args:拡張ファイル(*.crx)のパスの追加
o.set_capability(name, value)
# ブラウザの環境設定を追加する
# それぞれのオプション名と値はここ:https://www.seleniumqref.com/api/java/about/About_capabilities.html
o.set_headless(headless=True)
# headlessモードを明示的にOnする(非推奨だけども…)
o.to_capabilities()
# プロクシ情報の追加
o.arguments
# 起動ブラウザに与えられた起動時オプション(add_argumentsとかで)を返す
o.binary_location
# ブラウザの実行バイナリの場所を指定する
# o.binary_location="././././chrome.exe"
o.capabilities
# 設定されているすべてのオプションを使用して環境設定を辞書型で返す
o.debugger_address
# リモートのdevtoolインスタンスのアドレスを返す
o.experimental_options
# Chromeの使用可能な実験的オプションの一覧を返す
# add_experimental_option(name, value)で追加
o.extensions
# エンコード済みの追加された拡張の一覧を返す
o.headless
# HeadlessモードがOnかどうかを返す
d = webdriver.Chrome("chromedriver",chrome_options=o)
d.add_cookie(cookie_dict)
# 今のセッションで用いたいCookieを指定
# cookie_dict: 必須の辞書オブジェクト
# keys - "name" and "value"
# optional keys - "path", "domain", "secure", "expiry"
# driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
# driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})
# driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})
d.back()
# ブラウザ履歴の1つ前に遷移
# driver.back()
d.close()
# ウィンドウを閉じる
# driver.close()
d.create_web_element(element_id)
# 指定されたelement_idでWeb要素を作成
d.delete_all_cookies()
# 現在のセッションでのCookieを全削除
# driver.delete_all_cookies()
d.delete_cookie(name)
# 指定された名前のCookieを削除
# driver.delete_cookie('my_cookie')
d.execute(driver_command, params=None)
# command.CommandExecutorのコマンドをドライバーで実行
# driver_command: 実行するコマンド(文字列型)
# params: コマンドの引数の辞書
# コマンドのJSON responseが辞書型として返る
d.execute_async_script(script, *args)
# 現在のウィンドウ/フレームでJavaScriptを非同期的に実行
# script: 実行するJavascriptのコード
# *args: scriptの実行時引数
# script = "var callback = arguments[arguments.length - 1];"
# script = "window.setTimeout(function(){ callback('timeout') }, 3000);"
d.execute_script(script, *args)
# 現在のウィンドウ/フレームでJavaScriptを同期的に実行
# script: 実行するJavascriptのコード
# *args: scriptの実行時引数
# driver.execute_script('return document.title;')
d.file_detector_context(**kwds)
# 必要な場合にのみ、限られた文脈で現在のファイルディテクタを上書きし、後で元のものが再設定されるようにする
# file_detector_class - 目的のファイル検出器のクラス
# クラスが現在のfile_detectorと異なる場合、
# クラスはargsとkwargsでインスタンス化され、コンテキストマネージャーの実行中にファイル検出器として使用される
# args - インスタンス化中にファイル検出クラスに渡されるオプションの引数
# kwargs - キーワード引数(argsと同じ方法で渡される)
# with webdriver.file_detector_context(UselessFileDetector):
# d.someinput.send_keys('/etc/hosts')
d.find_element(by='id', value=None)
# 与えられたby〇〇の方法で要素を検索
# 可能であればfind_element_by_*が優先
# find_element系は見つかった要素のWebElementが返る
# 見つからなかったらNoSuchElementException
# element = driver.find_element(By.ID, 'foo')
# WebElementが返る
d.find_element_by_class_name(name)
# class名で要素を検索
# name: 検索する要素のクラス名
# element = driver.find_element_by_class_name('foo')
d.find_element_by_css_selector(css_selector)
# CSSセレクタで要素を検索
# css_selector - CSSセレクタの文字列
# element = driver.find_element_by_css_selector('#foo')
d.find_element_by_id(id_)
# idで要素を検索
# id_ - 見つけたい要素のid
# element = driver.find_element_by_id('foo')
d.find_element_by_link_text(link_text)
# リンクテキストで要素を検索
# link_text: 見つけたい要素のリンクテキスト
# element = driver.find_element_by_link_text('Sign In')
d.find_element_by_name(name)
# name属性で要素を検索
# name: 見つけたい要素のname属性
# element = driver.find_element_by_name('foo')
d.find_element_by_partial_link_text(link_text)
# リンクテキスト(部分一致)で要素を検索
# link_text:見つけたい要素の部分リンクテキスト
# element = driver.find_element_by_partial_link_text('Sign')
d.find_element_by_tag_name(name)
# タグ名で要素を検索
# name - htmlタグの名前 (例: h1, a, span)
# element = driver.find_element_by_tag_name('h1')
d.find_element_by_xpath(xpath)
# xpathで要素を検索
# xpath - 見つけたい要素のxpathロケーター
# element = driver.find_element_by_xpath('//div/td[1]')
d.find_elements(by='id', value=None)
# find_elementsの、見つかった1個以上の要素が返る
# WebElementのリストになって返ってくる版
# find_elementだと1つの要素のWebElementのみ返ってくる
# 上記のfind_element*メソッドをfind_elements*に書き換えるとよい
# elements = driver.find_elements(By.CLASS_NAME, 'foo')
d.forward()
# ブラウザ履歴の1つ先へ遷移
# driver.forward()
d.fullscreen_window()
# 「フルスクリーン」操作(F11とかの)を呼び出す
d.get(url)
# 現在のブラウザセッションでのWebページの読み込み
d.get_cookie(name)
# 名前から単一のCookieを取得
# 見つかればCookieの値, 見つからなければNoneを返す
# driver.get_cookie('my_cookie')
d.get_cookies()
# 現在のセッションのCookieの辞書集合を返す
# driver.get_cookies()
d.get_log(log_type)
# 特定の種類のログを取得
# log_type: 返るログの種類
# driver.get_log('browser')
# driver.get_log('driver')
# driver.get_log('client')
# driver.get_log('server')
d.get_screenshot_as_base64()
# 現在ウィンドウのスクリーンショットを取る(base64形式)
# base64文字列が返るのでHTMLに埋め込むのに向いている
# driver.get_screenshot_as_base64()
d.get_screenshot_as_file(filename)
# 現在ウィンドウのスクリーンショットを取る(PNG形式)
# IOErrorならFalse,そうでなければTrueが返る
# filename: スクリーンショッットの保存先画像ファイルの絶対パス(.png拡張子)
# driver.get_screenshot_as_file('/Screenshots/foo.png')
d.get_screenshot_as_png()
# 現在ウィンドウのスクリーンショットを取る(PNGバイナリ形式)
# 返り値がPNGファイルのバイナリ
# driver.get_screenshot_as_png()
d.get_window_position(windowHandle='current')
# 現在ウィンドウのx,y位置を取得
# 取得する座標位置はウインドウ左上隅
# driver.get_window_position()
d.get_window_rect()
# 現在ウィンドウの高さと幅と同じウィンドウを開きx,y座標を取得
# driver.get_window_rect()
d.get_window_size(windowHandle='current')
# 現在ウィンドウの幅と高さを取得
# driver.get_window_size()
d.implicitly_wait(time_to_wait)
# ドライバーが要素を検索して読み込むまでの待機時間の上限を設定
# 1セッションにつき1回のみ実行される
# execute_async_scriptの読み込みのために設定するならset_script_timeoutを使うべし
# time_to_wait: 秒単位での待機時間
# driver.implicitly_wait(30)
d.maximize_window()
# 現在ウィンドウ最大化
d.minimize_window()
# "最小化"に当たる機能の呼び出し
d.quit()
# ドライバを終了しウィンドウを閉じる
# driver.quit()
d.refresh()
# 現在ページを再読込する
# driver.refresh()
d.save_screenshot(filename)
# save_screenshot_as_fileと同機能
# driver.save_screenshot('/Screenshots/foo.png')
d.set_page_load_timeout(time_to_wait)
# ページ読み込みが完了するまでの時間を設定しエラーを投げる
# time_to_wait: 秒単位での待機時間
# driver.set_page_load_timeout(30)
d.set_script_timeout(time_to_wait)
# ドライバがexecute_async_scriptで非同期処理を実行終了するまでの時間を設定しエラーを投げる
# time_to_wait: 秒単位での待機時間
# driver.set_script_timeout(30)
d.set_window_position(x, y, windowHandle='current')
# 現在ウィンドウの位置をx,y座標で設定する
# x: 現在ウィンドウの位置調整のためのx座標(px単位)
# y: 現在ウィンドウの位置調整のためのy座標(px単位)
# driver.set_window_position(0,0)
d.set_window_rect(x=None, y=None, width=None, height=None)
# 現在ウィンドウの位置、幅、高さを設定する
# driver.set_window_rect(x=10, y=10)
# driver.set_window_rect(width=100, height=200)
# driver.set_window_rect(x=10, y=10, width=100, height=200)
d.set_window_size(width, height, windowHandle='current')
# 現在ウィンドウの幅と高さを設定する
# width: ウィンドウの幅(px単位)
# height: ウィンドウの高さ(px単位)
# driver.set_window_size(800,600)
d.start_client()
# 新しいセッションの起動時に呼び出される
# カスタム起動の動作を定義する際に上書き可能なメソッド
d.start_session(capabilities, browser_profile=None)
# 目的の機能を持つ新しいセッションを作成
# browser_name - セッション開始要求をするブラウザ名
# version - セッション開始要求をするバージョン
# platform - ブラウザを要求するプラットフォーム名
# javascript_enabled - 新しいセッションでJavaScriptを有効にするか否か
# browser_profile - selenium.webdriver.firefox.firefox_profile.FirefoxProfileオブジェクト(Firefoxのみ)
d.stop_client()
# d.quit()の使用後に呼び出される
# カスタムシャットダウンの動作を定義する際に上書き可能なメソッド
d.switch_to_active_element()
# 非推奨=>driver.switch_to.active_elementへ
d.switch_to_alert()
# 非推奨=>driver.switch_to.alertへ
d.switch_to_default_content()
# 非推奨=>driver.switch_to.default_contentへ
d.switch_to_frame(frame_reference)
# 非推奨=>driver.switch_to.frameへ
d.switch_to_window(window_name)
# 非推奨=>driver.switch_to.windowへ
d.application_cache
# ブラウザ上のアプリケーションのキャッシュを扱うためのApplicationCacheオブジェクトを返す
d.current_url
# 現在ページのURLを返す
# driver.current_url
d.current_window_handle
# 現在ウィンドウのハンドルを返す
# ドライバの全ウィンドウのハンドルが欲しいならd.window_handlesへ
# driver.current_window_handle
d.desired_capabilities
# 使用中のドライバの望ましい機能を返す
d.file_detector
d.log_types
# 利用可能なログタイプのリストの取得
# driver.log_types
d.mobile
d.name
# ドライバのインスタンスのブラウザ名を返す
# name = driver.name
d.orientation
# 端末の現在の向きを取得
# orientation = driver.orientation
d.page_source
# 現在ページのソースを取得
# driver.page_source
d.switch_to
# SwichToオブジェクトを返す
# SwitchTo: フォーカスを切り替えるすべてのオプションを含むオブジェクト
# 現在のウィンドウの切り替えを行う
# element = driver.switch_to.active_element
# alert = driver.switch_to.alert
# driver.switch_to.default_content()
# driver.switch_to.frame('frame_name')
# driver.switch_to.frame(1)
# driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
# driver.switch_to.parent_frame()
# driver.switch_to.window('main')
d.title
# 現在のページタイトルを返す
# title = driver.title
d.window_handles
# 現在のセッションでの全ウィンドウの個別ハンドルを返す
# driver.window_handles
# find_elements?_by_*して得たWebelementに対する操作
# find_element(by='id', value=None)
# find_element_by_class_name(name)
# find_element_by_css_selector(css_selector)
# find_element_by_id(id_)
# find_element_by_link_text(link_text)
# find_element_by_name(name)
# find_element_by_partial_link_text(link_text)
# find_element_by_tag_name(name)
# find_element_by_xpath(xpath)
# find_elements(by='id', value=None)
# find_elements_by_class_name(name)
# find_elements_by_css_selector(css_selector)
# find_elements_by_link_text(link_text)
# find_elements_by_name(name)
# find_elements_by_partial_link_text(link_text)
# find_elements_by_tag_name(name)
# find_elements_by_xpath(xpath)
clear()
# Clears the text if it’s a text entry element.
click()
# Clicks the element.
get_attribute(name)
# Gets the given attribute or property of the element.
# name - Name of the attribute/property to retrieve.
# Check if the "active" CSS class is applied to an element.
# is_active = "active" in target_element.get_attribute("class")
get_property(name)
# Gets the given property of the element.
is_displayed()
# Whether the element is visible to a user.
is_enabled()
# Returns whether the element is enabled.
is_selected()
# Returns whether the element is selected.
# Can be used to check if a checkbox or radio button is selected.
screenshot(filename)
# Saves a screenshot of the current element to a PNG image file. Returns
# element.screenshot(‘/Screenshots/foo.png’)
send_keys(*value)
# Simulates typing into the element.
# Args: value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path.
# driver.find_element_by_name('username').send_keys("admin")
# driver.find_element_by_name('profilePic').send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
submit()
# Submits a form.
value_of_css_property(property_name)
# The value of a CSS property.
id
# Internal ID used by selenium.
# This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using ==:
# if element1 == element2: print("These 2 are equal")
location
# The location of the element in the renderable canvas.
location_once_scrolled_into_view
# THIS PROPERTY MAY CHANGE WITHOUT WARNING.
# Use this to discover where on the screen an element is so that we can click it.
# This method should cause the element to be scrolled into view.
# Returns the top lefthand corner location on the screen, or None if the element is not visible.
parent
# Internal reference to the WebDriver instance this element was found from.
rect
# A dictionary with the size and location of the element.
screenshot_as_base64
# Gets the screenshot of the current element as a base64 encoded string.
# Usage: img_b64 = element.screenshot_as_base64
screenshot_as_png
# Gets the screenshot of the current element as a binary data.
# Usage: element_png = element.screenshot_as_png
size
# The size of the element.
tag_name
# This element’s tagName property.
text
# The text of the element.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment