Published Date : 2020年9月7日16:39

【python】ウェブスクレイピングにも使えて、RPAにも応用できるSeleniumの扱い方
How to handle Selenium, which can be used for web scraping and also for RPA


This blog has an English translation


YouTubeにアップした動画、「【python】ウェブスクレイピングにも使えて、RPAにも応用できるSeleniumの扱い方」の補足説明の記事です。

Here's a little more about the 「【python】How to handle Selenium, which can be used for web scraping and also for RPA」 video I uploaded to YouTube.


目次

Table of Contents




① 動画の説明
① Video Description



ウェブスクレイピングだけでなく、RPAにも使えそうなブラウザ操作用ライブラリSeleniumを紹介します。

I introduce Selenium, a browser manipulation library that can be used for RPA as well as web scraping.

まずPipでPython用のSeleniumをインストールしてください。

First install Selenium for Python with Pip.

pip install selenium

GoogleChromeをSeleniumで操作できるように専用のドライバーをインストールします。

Install a dedicated driver to run Google Chrome on Selenium.

GoogleChromeの[設定]から[Chromeについて]を選択して、ご自身が使っているGoogleChromeのバージョンを調べておいてください。

Select [About Chrome] from the [Settings] section of Google Chrome, and check the version of Google Chrome you use.

同じバージョンのドライバーをダウンロードして解凍し、プロジェクトのフォルダに移動しておいてください。

Download and extract the same version of the driver and move it to the project folder.

それではテスト用に簡単なスクリプトを試してみましょう。

Let's try a simple test script.

適当なpythonファイルを作成する。

Create an appropriate python file.

seleniumのwebdriverから、Chromeブラウザで実行できるようにするためのモジュールをインポートする。

Imports a module from the selenium webdriver that allows it to run in the Chrome browser.

ヘッドレス(ブラウザを表示しないで実行できる)やシークレットモード等、色々なオプションが指定できます。

You can specify various options such as headless (Can run without browser) or secret mode.

今回は試しにシークレットモードでクロームを使用してみる。ヘッドレスを試したいなら[--headless]と指定する。

Here's how to use Chrome in Secret Mode. If you want to try headless, specify [--headless].

先ほどダウンロードしたクロームドライバーの実行ファイルへのパスを引数に渡す。

Pass the path to the ChromeDriver executable that you just downloaded as an argument.

するとブラウザが立ち上がるので、getメソッドでアクセスしたいURLを指定する。

Then, The browser will then launch, and you can use the get method to specify the URL you want to access.

# seleniumのwebdriverから、Chromeブラウザで実行できるようにするためのモジュールをインポートする。
# Imports a module from the selenium webdriver that allows it to run in the Chrome browser.
from selenium.webdriver import Chrome, ChromeOptions

# ヘッドレス(ブラウザを表示しないで実行できる)やシークレットモード等、色々なオプションが指定できます。
# You can specify various options such as headless (Can run without browser) or secret mode.
options = ChromeOptions()
# 今回は試しにシークレットモードでクロームを使用してみる。ヘッドレスを試したいなら[--headless]と指定する。
# Here's how to use Chrome in Secret Mode. If you want to try headless, specify [--headless].
options.add_argument('--incognito')

# 先ほどダウンロードしたクロームドライバーの実行ファイルへのパスを引数に渡す。
# Pass the path to the ChromeDriver executable that you just downloaded as an argument.
driver = Chrome(executable_path="your driver path", options=options)

# するとブラウザが立ち上がるので、getメソッドでアクセスしたいURLを指定する。
# Then, The browser will then launch, and you can use the get method to specify the URL you want to access.
driver.get('url')

スクリプトを実行してみましょう。

Let's run the script.

コマンドプロンプトに[python selenium_test.py]と入力して実行してみてください。

Try running this script by typing [python selenium_test.py] at the command prompt.

では動作を確認したので、今度はインタラクティブに実行していきましょう。

Now that you've seen how it works, let's do it interactively.

インタラクティブに実行してみたいときは、Pythonインタラクティブシェルでseleniumの実行もできます。

If you want to run it interactively, you can also run selenium in the Python interactive shell.

inputfilefield = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//input[@id="input-file-now"]')))
# ちなみに、もしinputタグのdisplay属性がnoneになっているならJavascriptを使って表示させることもできます。
# By the way, if the display attribute of the input tag is set to none, it can be displayed using Javascript.
driver.execute_script("arguments[0].style.display = 'block';", inputfilefield)

inputfilefield.send_keys(upload_image_file_path)

ご覧の通り、DOMの挙動によって、すぐに例外を発したり、requestsやScarapyより遅いです。

As you can see, DOM behavior can cause immediate exceptions and is slower than requests or Scarapy.

ですが、スクリプトでブラウザを直接操作できる利点は、AJAX等が使わているサイトで効果を発揮します。

However, the ability to interact directly with the browser works well for sites using AJAX and other technologies.

例えば、URLによってページ送りを判別できない場合、つまりクリックによって画面が切り替わることでページを切り替えるサイトの場合です。

For example, if you cannot determine the page feed by the URL, that is, a site that switches pages by clicking.

では今度はログインしたり、画像ファイル等をアップロードしたりして、簡易的なRPAのようなものを作っていきましょう。

Now let's create something like a simple RPA by logging in and uploading image files.

取得したウェブドライバーエレメントのSendKeysメソッドを使えば文字やファイルをブラウザに送ることができます。

You can use the SendKeys method on the web driver element to send characters and files to the browser.

Selectタグの場合の操作は、Selectクラスを使用します。

For the Select tag, the operation uses the Select class.

このようにSelectオブジェクトに変換し直してから、Optionのインデックスを指定すれば簡単にSelectタグのオプションが操作できます。

You can easily manipulate the options in the Select tag by converting it back to a Select object and then specifying the Option index.

もしインデックスの関係が分かりにくいのであれば、inputメソッドを使ってみてください。こうすれば、ユーザーからの入力にも応用できます。

If the relationship between indexes is hard to understand, try using the input method. It can then be applied to user input.

input_stock = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//select[@id="inputStock"]')))
input_stock = Select(input_stock)
# index(0) = 1, index(98) = 99
# もし分かりにくいのであれば、下記のようにすればいい。こうすれば、ユーザーからの入力にも応用できます。
"""
option_value = 9 # 1~99
input_stock.select_by_index(option_value-1)

# user input
option_value = input("Enter number (1-99): ")
input_stock.select_by_index(int(option_value)-1)
"""
input_stock.select_by_index(9)

savebtn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[@type="submit" and @value="Save"]')))
savebtn.click()

WebDriverWaitを使えば、アップロードしたイメージが画面に表れるまで待機してから、次の操作に移ることもできます。

With WebDriverWait, you can wait until the uploaded image appears on the screen before moving on to the next step.

try:
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="card-img-top"]/img')))
except:
    driver.quit()


以上です。お疲れ様です。

That's all. Thank you for your hard work.