LoginSignup
1
1

More than 3 years have passed since last update.

RubyのSeleniumでAttributeの値を変更したい

Posted at

概要

RubyのSeleniumでスクレイピングの処理を書いているときにどうしても属性値の変更を行いたくなる場面があります。UIの振る舞いを忠実に追跡したい場合では使いませんが、UIの挙動がわかっている場合に面倒な処理を飛ばして目的のものをすぐ欲しいという場合に有効です。

方法

RubyでAttributeへのアクセスはGetAttributeがあるにも関わらずSetAttributeが見つかりません。(探し方の問題かもしれませんが)GetではDOMに変更を与えませんが書き込みでは予期せぬ振る舞いを起こす可能性から用意されていないのではと勝手に推測し、今回は「execute_script」を使用します。

execute_script.rb
#ドライバーの初期化
client = Selenium::WebDriver::Remote::Http::Default.new
driver = Selenium::WebDriver.for :chrome, http_client: client

#<div id="mw-content-text" lang="ja" dir="ltr" class="mw-content-ltr">
#jaをenに変えたい

#対象になる要素の取得
target_element = driver.find_element(:class_name, 'mw-content-ltr')
driver.execute_script("arguments[0].setAttribute('lang', 'en');", target_element)

参考

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