9
14

More than 3 years have passed since last update.

[Python+Selenium]スクレイピングで使える小技メモ

Posted at

この記事について

実務でスクレイピングを行うことがあったので、その際にインプットした小技のメモです。

ツール

Python3(3.6.2)
Selenium
Chrome driver(85.0.4183.87)

1.jsを操作する(非表示要素を表示させる)

execute_scriptメソッドを使うことでSeleniumからJavascriptを操作することができます。

例えば、下記のようにjsのsetAttributeメソッドを操作してテキストの色を変えることができます。

from selenium import webdriver
driver = webdriver.Chrome()

driver.get("https://www.hogefuga")

element = driver.find_element_by_xpath("//div[@class='fuga']/span")
driver.execute_script("arguments[0].setAttribute('style','color: red;')", element)

このメソッドを活用すれば、display: none;になっている要素を表示させることもできます。例えばdisplay:none;が適用されているclass名を非表示となっている要素から削除することで非表示要素を表示させることができます。

# closeクラスにdisplay:none;が適用されている場合
element = driver.find_element_by_xpath("//div[@class='hoge close']/span")
driver.execute_script("arguments[0].setAttribute('class','hoge')", element)

2.iframe内の要素を取得する

ifame内の要素を取得するには、switch_to_frame()が必要です。

driver.switch_to_frame(driver.find_element_by_xpath("//div[@class='hoge']/iframe"))

これでifame内の要素を取得可能な状態にすることができます。一方でiframe外の要素は取得できなくなります。そのため、元の要素を取得したい場合はswitch_to_default_content()によって再び元の要素を取得できるように切り替える必要があります。

driver.switch_to_default_content()

3.Seleniumの操作対象を別ウィンドウに切り替える

seleniumを操作してスクレイピングする際に、リンクをクリック後に別ウインドウが開く場合があります。別ウインドウに対して何らかの操作を行いたい場合は、switch_to_window()によって操作対象を別ウインドウに切り替えます。

#別ウインドウを開く
driver.find_element_by_xpath("//div[@class='hoge']/a").click()

#当初から開いているウインドウ
window_before = driver.window_handles[0]
#新しく開いているウインドウ
window_after = driver.window_handles[1]

#seleniumの操作対象を新しく表示されたウインドウに切り替える
driver.switch_to_window(window_after)

#seleniumの操作対象を当初から開いているウインドウに切り替える
driver.switch_to_window(window_before)

4.ラジオボタンをクリック

# ラジオボタン要素を取得
element = driver.find_element_by_id(fugafuga)

driver.execute_script("arguments[0].click();", element)

5.HeadlessChromeでWEBページからファイルをダウンロードする

HeadlessChromeはセキュリティ上の観点からデフォルトではファイルのダウンロード機能は実装されていないようです。そのためpost通信によってファイルダウンロードを許可する設定を行う必要があるようです。

from selenium import webdriver

DOWNLOAD_URL = "https:www.hogefuga/file/download"
download_dir = "/home/download"  #ダウンロードしたファイルの置き場所

def enable_download(driver, download_dir):
    driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
    params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
    driver.execute("send_command", params)

def setting_chrome_options():
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument('--no-sandbox')
    return chrome_options;

driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver",options=setting_chrome_options())
enable_download(driver, download_dir)
driver.get(DOWNLOAD_URL)

※executable_pathは各々の環境に合わせて変更してください。

9
14
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
9
14