Selenium Scraping:单击“下一步”按钮

问题描述 投票:0回答:1

我正在尝试在

https://www.federalreserve.gov/newsevents/pressreleases.htm
上抓取美联储的新闻稿,并且要抓取前几年的文件,我需要通过单击页面底部的 Next 按钮进入下一页。

我尝试了一些方法,但所有方法都返回

Message: no such element: Unable to locate element:
错误,并且我无法找出问题所在:

#Attempt 1
    driver.find_element_by_css_selector('.pagination-next ng-scope').click()
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".pagination-next ng-scope"))).click()

#Attempt 2
    driver.find_element_by_xpath("//*[@id='article']/ul[2]/li[7]/a").click()

#Attempt 3
    element=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH ,"//*[@id='article']/ul[2]/li[7]/a")))
    element.click()

有人可以帮我解决我哪里出错了吗?为了方便起见,Next 按钮的 HTML 为:

<li ng-if="::directionLinks" ng-class="{disabled: noNext()||ngDisabled}" class="pagination-next ng-scope"><a href="" ng-click="selectPage(page + 1, $event)" ng-disabled="noNext()||ngDisabled" uib-tabindex-toggle="" class="ng-binding">Next</a></li>
     <a href="" ng-click="selectPage(page + 1, $event)" ng-disabled="noNext()||ngDisabled" uib-tabindex-toggle="" class="ng-binding">Next</a>

谢谢

python selenium-webdriver web-scraping
1个回答
0
投票

文本为 Next 的元素是一个

<a>
标签,并且是一个 Angular 元素。

<a href="" ng-click="selectPage(page + 1, $event)" ng-disabled="noNext()||ngDisabled" uib-tabindex-toggle="" class="ng-binding">Next</a>

解决方案

要单击元素,您需要为 element_to_be_clickable() 引入 WebDriverWait,并且您可以使用以下任一定位器策略

  • 使用LINK_TEXT

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Next"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.pagination-next.ng-scope a.ng-binding"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Next']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.