[Ruby] I want to change the value of Attribute with Selenium of Ruby

less than 1 minute read

Overview

While writing scraping process in Selenium of Ruby, there is a scene where you want to change the attribute value. It is not used when you want to faithfully track the behavior of the UI, but it is effective when you want to skip the troublesome process and want the desired one immediately if you know the behavior of the UI.

Method

Access to Attribute in Ruby cannot find SetAttribute even though GetAttribute exists. (It may be a problem of how to search) Get does not change the DOM but it is unexpectedly not prepared due to the possibility of unexpected behavior in writing, so this time “execute_script” To use.

execute_script.rb


# Driver initialization
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">
I want to change #ja to en

# Get target element
target_element = driver.find_element(:class_name,'mw-content-ltr')
driver.execute_script("arguments[0].setAttribute('lang','en');", target_element)

reference

https://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium%2FWebDriver%2FDriver:execute_script