當前位置:成語大全網 - 新華字典 - python+selenium 分頁查詢時,把頁碼按位數拆分後執行了,怎麽解決?

python+selenium 分頁查詢時,把頁碼按位數拆分後執行了,怎麽解決?

樓主的需求似乎是點擊百度貼吧壹下,輸出當前頁面的尾數

先給樓主代碼(代碼以足球吧為例):

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

from selenium.common.exceptions import StaleElementReferenceException

driver = webdriver.Chrome()

driver.get("/f?ie=utf-8&kw=%E8%B6%B3%E7%90%83&fr=search")

driver.maximize_window()

wait = WebDriverWait(driver, 10)

for i in range(1, 10):

print("當前的尾頁數:", driver.find_element(By.XPATH,"//*[@id='frs_list_pager']/a[last()-2]").text)

try:

next_page_link = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "下壹頁>")))

next_page_link.click()

except StaleElementReferenceException:

next_page_link = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, "下壹頁>")))

next_page_link.click()

再解釋壹下這段代碼的業務邏輯:

使用 Selenium 打開百度貼吧的足球吧頁面。

最大化瀏覽器窗口。

創建壹個等待對象,設置最長等待時間為10秒。

使用循環,從第1頁到第9頁,執行以下操作:

打印當前頁的倒數第三個元素(即尾頁數)的文本內容。

使用等待對象,等待 "下壹頁>" 鏈接元素可見。

點擊 "下壹頁>" 鏈接元素,進入下壹頁。

如果在點擊之前頁面發生了變化(StaleElementReferenceException異常),重新等待並點擊 "下壹頁>" 鏈接元素。

總體來說,這段代碼的目的是模擬用戶在百度貼吧足球吧頁面翻頁,並打印每頁的尾頁數。通過使用等待操作,確保在頁面加載完成後再進行下壹步操作。

請註意,該代碼只展示了基本的翻頁和獲取尾頁數的邏輯,實際業務邏輯可能更加復雜,需要根據具體需求進行擴展和優化。