【发布时间】:2014-09-19 11:30:14
【问题描述】:
我一直在尝试在网页上定位一个元素,这个元素与其他元素具有相同的名称并且没有 id。它确实有不同的值,所以我想通过名称和值来查找元素。
在我的网页中,我有一个搜索按钮:
<input name="action" value=" Search " style=" border-style2; font-size: 11;
font-family: arial, helvetica" border="0" type="submit">
我不能使用名称,因为我有另一个具有相同名称和类型的元素:
<input name="action" value=" Go " onclick=" return custRange('cust', 'd_custno');"
style=" border-style2; font-size: 11; font-family: arial, helvetica"
border="0" type="submit">
因此我尝试使用 xpath,我首先使用 xpath 检查器返回返回的 xpath:
/x:html/x:body/x:center/x:table/x:tbody/x:tr/x:td/x:center/x:center[1]/x:table[2]/x:tbody/x:tr/x:td[1]/x:table[3]/x:tbody/x:tr[5]/x:td[2]/x:input[2]
再次对此很新,但我假设“x:”不应该在路径中,所以我删除了它并尝试找到具有以下内容的元素:
search = driver.find_element_by_xpath("//center[1]/table[2]/tbody/tr/td[1]/table[3]/tbody/tr[5]/td[2]/input[2]")
search.clickAndWait()
导致:
selenium.common.exceptions.NoSuchElementException: Message: 'Unable to find element with xpath == //center[1]/table[2]/tbody/tr/td[1]/table[3]/tbody/tr[5]/td[2]/input[2]'
所以我真的有 2 个问题,如果有人可以提供帮助,那就太好了:
- 有没有办法通过名称和值来识别元素?
- 显然我在 xpath 中遗漏了一些东西,我尝试使用 xpath 的方式不正确吗?如果是这样,你能建议我做错了什么吗?
非常感谢任何帮助。
为了完整起见,我的单元测试代码如下:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class umLoginTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Ie()
self.driver.implicitly_wait(3)
def test_login_to_um(self):
driver = self.driver
result_file = open("umLoginTest_result.txt", "w")
driver.get("http://ps-iweb/UserManage/Home")
self.assertIn("Welcome", driver.title)
elem = driver.find_element_by_name("userLogin")
elem.send_keys("pstevenson")
password = driver.find_element_by_name("sec_password")
password.send_keys("etc")
password.send_keys(Keys.RETURN)
test1 = driver.title
result_file.write(str(test1))
select = driver.find_element_by_name("conn_marketid")
for option in select.find_elements_by_tag_name('option'):
if option.text == 'Int Rate Swaps':
option.click()
search = driver.find_element_by_xpath("//center[1]/table[2]/tbody/tr/td[1]/table[3]/tbody/tr[5]/td[2]/input[2]")
search.clickAndWait()
result_file.close()
if __name__ == "__main__":
unittest.main()
【问题讨论】:
-
离题:不要使用同名的元素(是的,允许,但会产生很多怪癖)stackoverflow.com/questions/11111670/…
标签: python selenium python-3.x selenium-webdriver