I am practising my test automation on seleniumeasy.com I reached drag and drop slide bar but couldn't figure out how to move the bar value from 10 to 80. This is the code which I wrote but failed:
drag_ten = driver.find_element_by_xpath("//input[@value=10]")
drop_eighty = driver.find_element_by_xpath("//input[@value=80]")
ActionChains(driver).drag_and_drop(drag_ten, drop_eighty).perform()
Any help will be much appreciated.
One slider is still a single web element. Only the attributes values of that element are changing, when you shift the slider left or right. So in your code, drop_eighty would be undefined at the time of execution.
You could use drag_and_drop_by_offset or click_and_hold and specify the offset to slide the slider
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get('https://www.seleniumeasy.com/test/drag-drop-range-sliders-demo.html')
slider = driver.find_element_by_xpath('//div[@id="slider1"]//input')
ActionChains(driver).drag_and_drop_by_offset(slider, 250, 0).perform()
# Alternative: ActionChains(driver).click_and_hold(slider).move_by_offset(250, 0).release().perform()
However, finding a proper offset value is not that simple. It may also vary based on the window size. There are ways to calculate it, but it would complicate the answer too much.
A simpler option, in that case, would be to use the JavascriptExecutors execute_script method to change the value and then trigger the onchange listener. This option uses more meaningful values but it is specific to your slider implementation and it would need to be adjusted for any other slider implementations.
driver.execute_script('arguments[0].value = 80;', slider)
driver.execute_script('arguments[0].onchange();', slider)