首页 > 解决方案 > Selenium WebDriver 停止而不打印 XPath

问题描述

我正在尝试在控制台中打印 XPath 数据。但是即使没有错误,加载第一页后该过程也会停止。

这是我的代码:

browser.get('https://stackoverflow.com/questions?pagesize=10')
while True:
    try:
        elm = browser.find_element_by_link_text("next")
        elm.click()
        labels = browser.find_element_by_xpath('/html/body/div[3]/div[2]/div[1]/div[3]/div/div/div[1]/div[2]/h3/a')
        for label in labels:
            print label.text
    except:
        break

我错过了什么?

标签: pythonseleniummozillageckodriver

解决方案


没有收到任何错误的原因是因为您正在捕获它们然后只是使用break

您的问题标签的XPATH也有问题。我在链接中添加了一个滚动条next,以防您像我一样在底部收到 cookie 通知。这是一个工作示例:

注意:这是在 Python 3 中使用当前 Chrome build 67和 chromedriver 2.40进行的测试

import traceback
from selenium.common.exceptions import NoSuchElementException

browser.get('https://stackoverflow.com/questions?pagesize=10')
while True:
    try:
        elm = browser.find_element_by_link_text("next")
        browser.execute_script("return arguments[0].scrollIntoView();", elm)
        elm.click()
        labels = browser.find_elements_by_xpath('.//a[@class="question-hyperlink"]')
        for label in labels:
            print(label.text)
    except NoSuchElementException:
        print("only catching this exception now when you run out of the next elements, other exceptions will raise")
        print(traceback.format_exc())
        break

推荐阅读