使用 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)
关于python - 通过 Selenium 和 Webdriver 循环遍历 find_element_by_xpath() 的元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240272/