【问题标题】:Selenium WebDriver stops without printing XPathSelenium WebDriver 停止而不打印 XPath
【发布时间】:2024-04-30 08:35:02
【问题描述】:

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

这是我的代码:

browser.get('https://*.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

我错过了什么?

【问题讨论】:

  • 我猜你在第一次运行后遇到了异常,所以它会跳入 except 并打破你的循环。尝试不处理异常
  • 是的,试过了,但没有变化
  • 方法find_element_by_xpath返回单个元素或None。它不返回列表。

标签: python selenium mozilla geckodriver


【解决方案1】:

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

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

注意:这是在 Python 3 中使用当前 Chrome 版本 67 进行测试的,并且 chromedriver 2.40

import traceback
from selenium.common.exceptions import NoSuchElementException

browser.get('https://*.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

【讨论】:

  • 我得到错误:除了 NoSuchElementException as e: NameError: name 'NoSuchElementException' is not defined
  • 您必须导入它,尝试使用导入的更新代码。