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.
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.
# 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.setAttribute('lang','en');", target_element)