【问题标题】:Selenium NoSuchElementException with driver.find_element_by_xpath带有 driver.find_element_by_xpath 的 Selenium NoSuchElementException
【发布时间】:2016-04-29 22:28:50
【问题描述】:

第一个问题:如何让python最小化chrome?

第二个问题:当使用下一个按钮到达结束页面时,我如何告诉 python 继续..而不给我一个错误?

driver.get("https://www.google.com/#q=" + user_input)
for n in range(5):
    driver.find_element_by_xpath("""//*[@id="pnnext"]/span[2]""").click()
    time.sleep(2)
    posts2 = driver.find_elements_by_class_name("_Rm")
    for post2 in posts2:
        print(post2.text)
        text_file.write(post2.text + "\n")

执行此代码后,我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/Skid/PycharmProjects/untitled/2nd.py", line 20, in <module>
    driver.find_element_by_xpath("""//*[@id="pnnext"]/span[2]""").click()
  File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 258, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 712, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="pnnext"]/span[2]"}
  (Session info: chrome=47.0.2526.111)
  (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 10.0 x86_64)

【问题讨论】:

  • 您需要更具体。错误是什么?你从哪里得到的?
  • @guy 对此表示抱歉
  • 我想知道为什么人们否定代表,然而,他们没有帮助!
  • @Nevermind123 可能是因为您决定不遵循本网站上的简单规则。如果您想避免以后发生这种情况,请阅读the Help Center 中提供的内容。
  • 没关系,我只是讨厌每次收到 neg rep 时都创建新帐户,无论如何,有人知道如何解决吗?

标签: python python-3.x selenium


【解决方案1】:

您收到NoSuchElementException,驱动程序找不到您的元素。将您的 xpath 更改为此

driver.find_element_by_xpath("//*[@id='pnnext']/span[2]").click()

不带 3 个引号。

【讨论】:

  • @Nevermind123 好吧,如果没有我要求的 html,我真的无法为您提供更多帮助。 (并将其作为文本添加到您的问题中,我没有点击链接)。
  • 好吧,我明天问问;这只是一个 pastebin 链接,但我稍后会问什么,可能只是以某种方式自己修复它
  • 还有一件事你误解了,我有三页(但如果可以更多取决于我的搜索)我正在寻找它阅读它,如果它不在那里,那么什么都不做.. 因为 """ """ 有效。
  • @Nevermind123 如果你想让它在它不存在的情况下什么也不做,你应该把它放在try catch 块中,否则你会得到异常。
  • 好的,谢谢,试试:driver.find_element_by_xpath("//*[@id='pnnext']/span[2]").click() except: pass
猜你喜欢
  • 2013-11-24
  • 1970-01-01
  • 2023-03-10
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2020-04-24
  • 1970-01-01
相关资源
最近更新 更多