Hack Forums
[Python] Stale element in selenium - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Stale element in selenium (/showthread.php?tid=6123640)



Stale element in selenium - roosiinfidel09 - Nov 26, 2020

Please run this code if possible for you. This search gives names of people who are in a ban list of some sort. My code returns two names. My question is this. When I click on the first name, see his details, come back to the results to click on the second name, the element has become stale by then. I have tried Webdriverwait, implicitly wait, etc. I cannot use individual xpaths because for some other search there might be many results. So, how do I come back to result page and click on the next name, so on on so forth?

Code
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser_options = Options()
browser_options.add_argument('--user-agent="Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36"')
browser_options.add_argument('start-maximized')
browser = webdriver.Chrome(executable_path='C:/bin/chromedriver.exe',options=browser_options)
browser.get('https://sanctionssearch.ofac.treas.gov/default.aspx')
search_box = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ctl00_MainContent_txtLastName"]')))
search_box.send_keys('Saleem')
search_box.send_keys(Keys.ENTER)
time.sleep(4)
buttons_list = []
try:
    results = browser.find_element_by_xpath('//*[@id="gvSearchResults"]/tbody').find_elements_by_tag_name('td')
    for result in results:
        buttons = result.find_elements_by_id('btnDetails')
        for button in buttons:
            buttons_list.append(button)
            
    for item in buttons_list:
        item.click()
        time.sleep(5)
        browser.back()
        browser.refresh()
finally:
    browser.quit()



RE: Stale element in selenium - john__john - Aug 19, 2021

I can help you, PM me pls