使用 Python、Selenium 和 Webdriver,需要在网页上使用 find_element_by_xpath() 方法随后单击文本找到的元素。
(公司内部网页,无法提供网址)
通过 xpath 是最好的方式,但有多个文本我想定位并单击。
它在分开时有效,例如:
driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click()
对于多个,这是我尝试过的:
name_list = ["Kate", "David"]
for name in name_list:
xpath = "//*[contains(text(), '"
xpath += str(name)
xpath += "')]"
print xpath
driver.find_element_by_xpath(xpath).click()
time.sleep(5)
打印 xpath 的输出看起来不错,但是 selenium 说:
common.exceptions.NoSuchElementException
请您参考如下方法:
您可以简化您的代码如下:
for name in name_list:
driver.find_element_by_xpath("//*[contains(text(), '%s')]" % name).click()
或
for name in name_list:
try:
driver.find_element_by_xpath("//*[contains(text(), '{}')]".format(name)).click()
except:
print("Element with name '%s' is not found" % name)
