问题陈述:我试图通过浏览网站上的各个链接来搜索数据,直到我到达对应于指向"患者列表"的超文本引用的下面一段代码。
<td height="20" align="middle" nowrap="">
<a href="javascript:goPatientList()"><b>Patient List</b></a>
</td>
我复制了超文本引用的xpath,如下面的代码所示。
以下部分有我的python代码。
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver=webdriver.Chrome()
driver.get("https://example.com")
print(driver.title)
username = driver.find_element_by_name('username')
username.send_keys("username")
password = driver.find_element_by_name("password")
password.send_keys("password")
driver.find_element_by_name("Login").click()
driver.find_element_by_id("tab5").click()
driver.find_element_by_id("menu5_3").click()
**driver.find_element_by_xpath("/html/body/form/table/tbody/tr/td/table/tbody/tr[1]/td[7]/a").click()**
我收到错误:
Traceback (most recent call last):
File "login.py", line 31, in <module>
driver.find_element_by_xpath("/html/body/form/table/tbody/tr/td/table/tbody/tr[1]/td[7]/a").click()
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 295, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 756, in find_element
'value': value})['value']
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 238, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_responseraise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/form/table/tbody/tr/td/table/tbody/tr[1]/td[7]/a"}
(Session info: chrome=56.0.2924.87)
(Driver info: chromedriver=2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f),platform=Mac OS X 10.11.6 x86_64)
有人可以查看这段代码并在此过程中指导我吗?
答案 0 :(得分:0)
NoSuchElementException
表示selenium无法找到该元素。很可能你使用的xpath是错误的。检查你的xpath。您还可以测试您的xpath,例如使用Firefox firebug扩展。
当我们与人类比较时,另一种可能性是硒很快。当selenium加载页面并点击可能没有按钮或关联javascript。所以我们可以告诉selenium稍等一下然后点击。所以在点击之前添加等待功能。
driver.find_element_by_name("Login").click()
driver.implicitly_wait(10)
答案 1 :(得分:0)
你需要学习如何制作正确的xpath。大多数时候,萤火虫不是最好的