When writing scraping process in Ruby's Selenium, there is a scene where you really want to change the attribute value. It is not used when you want to faithfully track the behavior of the UI, but it is useful when you know the behavior of the UI and want to skip the troublesome process and get the desired one immediately.
Access to Attribute in Ruby does not find SetAttribute even though it has GetAttribute. (It may be a problem of how to find it) Get does not change the DOM, but I guess that it is not prepared because it may cause unexpected behavior in writing, so this time I will use "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 the target element
target_element = driver.find_element(:class_name, 'mw-content-ltr')
driver.execute_script("arguments[0].setAttribute('lang', 'en');", target_element)
https://www.rubydoc.info/gems/selenium-webdriver/0.0.28/Selenium%2FWebDriver%2FDriver:execute_script
Recommended Posts