Selenium Webdriver:find_element_by_xpath找不到完整路径

时间:2017-02-15 18:08:42

标签: python-3.x selenium selenium-webdriver selenium-chromedriver

我正在使用Selenium 2.53.6和Chromedriver在动态网页上查找HTML DOM元素。我正在使用Webdriver的find_element_by_xpath()命令来定位元素。当它是单个元素时,如下例所示,find_element_by_xpath()定位元素。

city1 = driver.find_element_by_xpath("//div[@class='post-body-meta']")

但是,当我扩展路径以在DOM层次结构中包含更多元素时:

city1 = driver.find_element_by_xpath("//div[@class='post-body-meta']/span[0]")

然后我得到下面的错误(请记住,我已经尝试了很多不同的元素,而不仅仅是这个特定的元素):

Traceback (most recent call last):
  File "selen_decko.py", line 72, in <module>
    city1 = driver.find_element_by_xpath("//div[@class='post-body-meta']/span[0]")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 293, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
    'value': value})['value']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='post-body-meta']/span[0]"}
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.11.6 x86_64)

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x101468b70>>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 173, in __del__
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 149, in stop
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 120, in send_remote_shutdown_command

2 个答案:

答案 0 :(得分:0)

如此接近,但到目前为止。我需要find_elements_by_xpath。关键区别是elements而不是element。此外,索引似乎从1开始,而不是0:

city = driver.find_elements_by_xpath("//div[@class='post-body-meta']/span[1]/a")

答案 1 :(得分:0)

您是否通过Chrome的检查工具或Firefox的Firepath插件验证了xpath?没有看到HTML代码,我无法确定路径是否有效。