Ricard Le
Ricard Le

Reputation: 55

How to wait a page is loaded in Python Selenium

try:
    next_page_elem = self.browser.find_element_by_xpath("//a[text()='%d']" % pageno)

except noSuchElementException:
    break
print('page ', pageno)
next_page_elem.click()
sleep(10)

I have a page contains information about reports inside a frame. When i use sleep method to wait for next page to load it works, and without it i kept getting the information on page 1. Beside the sleep is there a better to do this in selenium. I have tried out some previous post that is similar but i think the html i have is quite unique please see example below. Selenium Python: how to wait until the page is loaded? Any help I would be much appreciated. Thanks

 <html>
        <div class="z-page-block-right" style="width:60%;">
        <ul class="pageingclass">
        <li/>
        <li>
        <a class="on" href="javascript:void(0)">1</a>
        </li>
        <li>
        <a onclick=" gotoPage('2','2')" href="javascript:void(0)">2</a>
        </li>
        <li>
        <a class=" next " onclick=" gotoPage('2','2')" href="javascript:void(0)"/>
        </li>
        </ul>
        </div>
    </html>

Upvotes: 1

Views: 19614

Answers (1)

alecxe
alecxe

Reputation: 473763

See this element:

<a class="on" href="javascript:void(0)">1</a>

From what I understand this basically means what page are we currently at.

Since we know the page number beforehand, the idea would be to wait until the element with the current page number becomes present:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
try:
    next_page_elem = self.browser.find_element_by_xpath("//a[text()='%d']" % pageno)

except noSuchElementException:
    break
print('page ', pageno)
next_page_elem.click()

# wait for the page to load
wait.until(
    EC.presence_of_element_located((By.XPATH, "//a[@class = 'on' and . = '%d']" % pageno))
)

Where //a[@class = 'on' and . = '%d'] is an XPath expression that would match a element(s) with class="on" and the text equal to the page number that we paste into the expression via string formatting.

Upvotes: 4

Related Questions