1
1

More than 1 year has passed since last update.

Selenium4のEdgedriverでデフォルトのダウンロードフォルダを変更する

Last updated at Posted at 2022-04-05

はじめに

以前、msedge_selenium_toolsを使うやり方の記事を書いたけど、selenium4でもできるらしいのでそちらに乗り換え。

準備

Edgedriverをダウンロード

PCにインストールされてるEdgeに対応するバージョンのEdgedriverをダウンロードしておく
https://developer.microsoft.com/ja-jp/microsoft-edge/tools/webdriver/

ライブラリのインポート

pip install selenium

※以下はMicrosoft公式のマニュアル。日本語翻訳は機械翻訳がアレなので英語版で読むのを推奨
https://docs.microsoft.com/en-us/microsoft-edge/webdriver-chromium/?tabs=python

やり方

experimenal_optionsに辞書型で色々変数が入っているみたいっぽいので、その値を上書きしてやる形で指定するっぽい。

#%%
#ライブラリのインポート
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options

#パラメータの準備
driverpath='./edgedriver/msedgedriver.exe'
prefs={"download.default_directory": "c:\\users\\username\\downloads"}

#設定
service = Service(executable_path=driverpath)
options = Options()
options.experimental_options["prefs"]=prefs

#driverの立ち上げ
driver = webdriver.Edge(service=service,options=options)
 
#urlに遷移
driver.get('https://www.bing.com/')

#driverの終了
driver.quit()

おわりに

Microsoftの公式マニュアルをサクサク読みこなせるような、行間を読む力が欲しい。
EdgeじゃなくてもChromeでも同じようなことができるとは思う。

おまけ

たまに、ボタンを押すと画面上にポップアップのように出てきて、その要素上の要素を触りたいのに、なぜか指定できない場合がある。そういう時は、iframeをスイッチする必要があるかもしれないので、driver.switch_toでうまいことする。

from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

#webdriverの立ち上げ
service = Service(executable_path=driverpath)
driver = webdriver.Edge(service=service,options=options)

#トップページに遷移
driver.get(url)

#要素を待ってボタン押下
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "要素ID")))
driver.find_element(By.ID, "要素ID").click()

#iframeを待ってスイッチ
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME,"<iframe>名")))
driver.switch_to.frame(driver.find_element(By.NAME,"<iframe>名"))

#要素の入力
driver.find_element(By.NAME,"<iframe>上の要素名").send_keys("hogehoge")   

補足

2022/05/16 19:28 driverを立ち上げるときにexecutable_pathを直接指定するとWarningが出るので、Serviceを使う方法に変更

1
1
2

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