Trying to get details of Tyres on this page. https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL . Each tyre has different FINITIONS. The price and other details are different for each FINITIONS. I would like to click on each FINITION type. The problem is that on clicking the FINITION type the links go stale, and You cannot refresh the page, if you do it will take you back to the starting page. So, How can I avoid stale element error without refreshing the page?
count_added = Falsebuttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]')fin_buttons = buttons_div[2].find_elements_by_xpath('.//button')fin_count = len(fin_buttons) if fin_count > 2:for z in range(fin_count):if not count_added:z = z + 2 #Avoid clicking the Titlecount_added = Truefin_buttons[z].click()finition = fin_buttons[z].texttime.sleep(2)driver.refresh() #Cannot do this. Will take to a different page
To clarify: the stale element is thrown because the element is no longer attached to the DOM. In your case is this: buttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]') that its being used as parent in the fin_buttons[z].click()
To solve this you'll have to "refresh" the element once the DOM changes. You can do that like this:
from selenium import webdriver
from time import sleepdriver = webdriver.Chrome(executable_path="D:/chromedriver.exe")driver.get("https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL")driver.maximize_window()driver.find_elements_by_xpath("//div[@class='card-body text-center']/a")[1].click()def click_fin_buttons(index):driver.find_elements_by_xpath('//div[@class="btn-group"]')[2].find_elements_by_xpath('.//button')[index].click()def text_fin_buttons(index):return driver.find_elements_by_xpath('//div[@class="btn-group"]')[2].find_elements_by_xpath('.//button')[index].textsleep(2)
count_added = False
buttons_div = driver.find_elements_by_xpath('//div[@class="btn-group"]')
fin_buttons = buttons_div[2].find_elements_by_xpath('.//button')
fin_count = len(fin_buttons)
if fin_count > 2:for z in range(fin_count):if not count_added:z = z + 2 #Avoid clicking the Titlecount_added = Trueclick_fin_buttons(z)finition = text_fin_buttons(z)sleep(2)print(finition)#driver.refresh() #Cannot do this. Will take to a different page