硒蟒蛇 - 执行操作,单击下一页,重复直到最后一页

我正在尝试对网页执行操作,单击“下一步”按钮,然后重复该操作,直到到达最后一页。我尝试过在堆栈溢出上使用类似问题的答案,但我无法让它们正常工作。现在唯一发生的事情是网页打开。我的代码都没有发生, 用网页做事.我的代码在下面。感谢您的帮助!从硒导入网络驱动程序从 webdriver_manager.chrome 导入 Chrome驱动程序管理器


driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('https://obamawhitehouse.archives.gov/briefing-room/speeches-and-remarks')


while True:

    next_page_btn = driver.find_elements_by_xpath("//li[@class = 'pagination-next']/a")

    if len(next_page_btn) < 1:

        print("No more pages left")

        break

    else:

        <MY CODE>

        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Next'))).click() 



哈士奇WWW
浏览 120回答 3
3回答

慕无忌1623718

我注意到我的网站的页面是这样描述的:https://obamawhitehouse.archives.gov/briefing-room/speeches-and-remarks?term_node_tid_depth=31&page=1转到 。因此,我能够将我的代码包装在一个 while 循环中,添加一个计数器,然后执行 .page=473page={}.format

烙印99

请检查以下解决方案供您参考:from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWait as Waitfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.common.exceptions import TimeoutExceptiondriver = webdriver.Chrome(executable_path=r"\chromedriver.exe")driver.get('https://obamawhitehouse.archives.gov/briefing-room/speeches-and-remarks')wait = WebDriverWait(driver,30)flag = Truewhile flag:&nbsp;try:&nbsp; &nbsp; element = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(text(),'Next')]")))&nbsp; &nbsp; if (element != 0):&nbsp; &nbsp; &nbsp; &nbsp; element.click()&nbsp;except TimeoutException as ex:&nbsp; &nbsp; &nbsp; &nbsp; print "It is all good, no element there"

慕妹3242003

我看了一下这个网站,似乎分页的下一个类并不存在。相反,您要查找的“下一步”按钮具有类寻呼机 - 下一个最后一个我建议然后改变这一点:next_page_btn&nbsp;=&nbsp;driver.find_elements_by_xpath("*//li[@class&nbsp;=&nbsp;'pagination-next']/a")为此:next_page_btn&nbsp;=&nbsp;driver.find_elements_by_xpath("*//li[@class&nbsp;=&nbsp;'pager-next&nbsp;last']/a")如果这有帮助,请告诉我!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python