1

My code:

count = 1
next_page_string = "javascript:__doPostBack('ctl00$MainContent$grdResults','Page$" + str(count) + "')"
td_page_number_list = driver.find_elements_by_xpath("//*[@id='MainContent_grdResults']/tbody/tr[22]/td/table/tbody/tr/td/a")
for x in td_page_number_list:
      if x.get_attribute("href") == next_page_string:
                driver.execute_script("__doPostBack('ctl00$MainContent$grdResults','Page$" + str(count) + "')")

The code is breaking when driver object goes to execute_script after the condition is met, giving me error:

stale element reference: element is not attached to the page document

It seems like this has something to do with the for loop in use. I have tried the implicit wait with no luck.

Thank you in advance.

dataviews
  • 2,466
  • 7
  • 31
  • 64
  • Handle `__doPostBack()` call with `staleness_of()` method following [How do I wait for a JavaScript __doPostBack call through Selenium and WebDriver](https://stackoverflow.com/questions/49561611/how-do-i-wait-for-a-javascript-dopostback-call-through-selenium-and-webdriver) – undetected Selenium Aug 23 '18 at 15:31

2 Answers2

0

Every time the script click one page number in the loop, the page changed and selenium treat it as new page. So those page numbers found on the page before click are invalid on new page.

To fix you problem, simple way is to find page numbers on new page again in each iteration of the loop.

count = 1
next_page_string = "javascript:__doPostBack('ctl00$MainContent$grdResults','Page$" 
                  + str(count) + "')"
td_page_number_list = driver.find_elements_by_xpath(
   "//*[@id='MainContent_grdResults']/tbody/tr[22]/td/table/tbody/tr/td/a")

for x in td_page_number_list:
  if x.get_attribute("href") == next_page_string:
    driver.execute_script("__doPostBack('ctl00$MainContent$grdResults','Page$" 
                  + str(count) + "')")

    // find page numbers on new page again after click
    // i think you need to add some wait before find again 
    // like: time.sleep(5) or using selenium wait api
    td_page_number_list = driver.find_elements_by_xpath(
           "//*[@id='MainContent_grdResults']/tbody/tr[22]/td/table/tbody/tr/td/a")
yong
  • 13,357
  • 1
  • 16
  • 27
0

I needed a simple break right after the driver.execute_script() method. In fact it was doing the __doPostBack, but the for loop was still executing after the if condition was met. All I needed to do is exit the loop once the condition is met, which you can achieve by using the break condition.

dataviews
  • 2,466
  • 7
  • 31
  • 64