[英]Loop over list of elements for find_element_by_xpath() by Selenium and Webdriver
With Python, Selenium and Webdriver, a need to subsequently click elements found by texts, using the find_element_by_xpath() way on a webpage. 使用Python,Selenium和Webdriver,需要随后使用网页上的find_element_by_xpath()方法单击文本找到的元素。
(an company internal webpage so excuse me cannot provide the url) (公司内部网页,所以无法提供该网址)
By xpath is the best way but there are multiple texts I want to locate and click. 通过xpath是最好的方法,但是我想找到并单击多个文本。
It works when separately like: 当单独运行时,它像:
driver.find_element_by_xpath("//*[contains(text(), 'Kate')]").click()
For multiple, here is what I tried: 对于多个,这是我尝试的方法:
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)
The output of the print xpath looked ok however selenium says: print xpath的输出看起来还不错,但是硒说:
common.exceptions.NoSuchElementException
You can simplify your code as below: 您可以如下简化代码:
for name in name_list:
driver.find_element_by_xpath("//*[contains(text(), '%s')]" % name).click()
or 要么
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)
Use string formatting. 使用字符串格式。 Put a placeholder into the xpath string and fill it with a variable value:
将占位符放入xpath字符串中,并用一个变量值填充它:
name_list = ["Kate", "David"]
for name in name_list:
xpath = "//*[contains(text(),'{}')]".format(name)
driver.find_element_by_xpath(xpath).click()
Try this: 尝试这个:
name_list = ["Kate", "David"]
for name in name_list:
xpath = "//*[contains(text(), '" + str(name) + "')]" # simplified
print xpath
list = driver.find_elements_by_xpath(xpath) # locate all elements by xpath
if len(list) > 0: # if list is not empty, click on element
list[0].click() # click on the first element in the list
time.sleep(5)
This will prevent from throwing 这样可以防止抛出
common.exceptions.NoSuchElementException
Note: also make sure, that you using the correct xPath. 注意:还请确保您使用正确的xPath。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.