简体   繁体   中英

Exit while true loop to exit when there is none more to click using Python and Selenium

I'm automating steps/click on a website using Python and Selenium.

I need a solution with the 'while true:' loop to exit when there is none more to click and to go to the next line of code.

I've been searching and tried everything I could but can't get this to work.

The web page I access and need automate has variable amount pages that changes daily. At the bottom of each page there is a 'view more' button. So far, the code I have does the job of scrolling down and clicking each button until there is no more to click.

Problem is the code exits on error when there are none more to click.

I will appreciate it if someone can help me with a solution please.

I'm a novice (but I'm trying) when it comes to Python(or any coding) so please be gentle and descriptive.

Thank you.

            from selenium import webdriver
            from selenium.webdriver.common.keys import Keys
            import time
            url = "https://web_page_i_want_to_open.html"
            username = 'abcdefgh'
            password = '123456'
            browser  = webdriver.Firefox()
            browser.get(url)
            time.sleep(5)
            #find and click username field and insert login name
            browser.find_element_by_xpath('/path_to_login_name_field').send_keys(username)

            #find and click password field and insert password
            browser.find_element_by_xpath('/path_to_password_field').send_keys(password)

            #click login button
            browser.find_element_by_xpath('"login-button"]').click()

            #find and click "view more" button at bottom of page
            while True:
                browser.find_element_by_xpath('/button_at_bottom_of_the_page').click()
                time.sleep(5)

            #click "some_other_button_on_the_page"
            #browser.find_element_by_xpath('/some_other_button_on_the_page').click()

Catch the no such element exception, and when you get that, assume no more pages.

while True:
    try:
        browser.find_element_by_xpath('/button_at_bottom_of_the_page').click()
        time.sleep(5)
    except NoSuchElementException:
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM