簡體   English   中英

使用 Python 和 Selenium 不再單擊時退出 while true 循環以退出

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

我正在使用 Python 和 Selenium 自動化步驟/單擊網站。

我需要一個帶有 'while true:' 循環的解決方案,當沒有更多可點擊時退出並轉到下一行代碼。

我一直在搜索並嘗試了所有我能做的但無法讓它工作。

我訪問並需要自動化的網頁具有每天變化的可變數量的頁面。 在每個頁面的底部都有一個“查看更多”按鈕。 到目前為止,我所擁有的代碼完成了向下滾動並單擊每個按鈕直到不再單擊為止的工作。

問題是當沒有更多可點擊時,代碼會因錯誤而退出。

如果有人可以幫助我解決問題,我將不勝感激。

當涉及到 Python(或任何編碼)時,我是一個新手(但我正在嘗試),所以請保持溫和和描述性。

謝謝你。

            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()

捕捉 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