[英]Selenium clicking next button programmatically until the last page
嗨,我是Web抓取的新手,並且一直在嘗試使用Selenium來抓取python中的論壇
我試圖讓Selenium單擊“下一步”,直到最后一頁,但是我不確定如何中斷循環。 我在定位器上遇到了麻煩:
當我通過部分鏈接找到下一個按鈕時,自動單擊將繼續到下一個線程,例如page1-> page2->下一個線程->下一個線程的page1->下一個線程的page2
while True:
next_link = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Next")))
next_link.click()
當我按類別名稱找到下一個按鈕時,自動單擊將在到達最后一頁時單擊“上一個”按鈕
while True:
next_link = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "prevnext")))
next_link.click()
我的問題是:
您可以使用任何提供唯一標識的定位器。 最佳做法按以下順序進行。
當找不到元素時可以退出while循環,可以使用try塊,如下所示。 break命令用於相同的命令。
while True: try: next_link = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "prevnext"))) next_link.click() except TimeoutException: break
您需要考慮以下幾點:
click()
而不是期望的條件(作為element_to_be_clickable()
presence_of_element_located()
,則需要使用element_to_be_clickable()
。 click()
中try-catch
塊和櫃面的異常break
了。 這是工作代碼塊:
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 options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\\Utility\\BrowserDrivers\\chromedriver.exe') driver.get("https://forums.hardwarezone.com.sg/money-mind-210/hdb-fully-paid-up-5744914.html") driver.find_element_by_xpath("//a[@id='poststop' and @name='poststop']//following::table[1]//li[@class='prevnext']/a").click() while True: try : WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='poststop' and @name='poststop']//following::table[1]//li[@class='prevnext']/a[contains(.,'Next')]"))).click() except : print("No more pages left") break driver.quit()
控制台輸出:
No more pages left
您可以使用以下代碼單擊“下一步”按鈕,直到到達最后一頁;如果不存在該按鈕,則中斷循環:
from selenium.common.exceptions import TimeoutException
while True:
try:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Next ›"))).click()
except TimeoutException:
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.