简体   繁体   English

使用 Python 和 Selenium 不再单击时退出 while true 循环以退出

[英]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.我正在使用 Python 和 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.我需要一个带有 'while true:' 循环的解决方案,当没有更多可点击时退出并转到下一行代码。

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.当涉及到 Python(或任何编码)时,我是一个新手(但我正在尝试),所以请保持温和和描述性。

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.捕捉 no such element 异常,当你得到它时,假设没有更多的页面。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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