如何在硒Python中单击页面链接

时间:2020-05-27 14:32:41

标签: python selenium

我正在尝试获取this page上的数据。 如您所见,共有5页,我想一一单击这些链接,然后获取表的数据。 但是我无法转到下一页。 我的代码如下所示。

page_counts = len(driver.find_elements_by_xpath("//tr[@class='pagerRow']/td/table/tbody/tr/td"))
next_page_no = 2
while True:
    ... 
    try:
       element = driver.find_element_by_xpath("//tr[@class='pagerRow']/td/table/tbody/tr/td[" + str(next_page_no) + "]/a")
       driver.execute_script("arguments[0].click();", element)
       next_page_no += 1
       time.sleep(2)
    except:
       break

如何单击每个页面链接?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

好吧,我没有测试过,但是在这一行之后: element = driver.find_element_by_xpath("//tr[@class='pagerRow']/td/table/tbody/tr/td[" + str(next_page_no) + "]/a")

如果找到的元素是可点击的,那么您应该可以使用element.click()方法。

答案 1 :(得分:0)

演示

import time

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get('https://eproperty.casey.vic.gov.au/T1PRProd/WebApps/eProperty/P1/eTrack/eTrackApplicationSearchResults.aspx?Field=S&Period=TM&r=P1.WEBGUEST&f=%24P1.ETR.SEARCH.STM')

current_page = 1
while True:
    pager = driver.find_element_by_css_selector('tr.pagerRow')
    links = pager.find_elements_by_xpath(f"//a[text()='{current_page+1}']")
    if not links:
        break

    a = links[0]
    ActionChains(driver).move_to_element(a).perform()
    a.click()
    time.sleep(5)
    current_page += 1

driver.quit()