简体   繁体   English

如何使用 Python 在 Selenium Webdriver 中高效迭代变量数?

[英]How to efficiently iterate variable number in Selenium Webdriver using Python?

I am using selenium webdriver with Python on IE and the code mentioned below is working fine but I need to make this in a loop.我在 IE 上使用带有 Python 的 selenium webdriver,下面提到的代码工作正常,但我需要在循环中进行。 Please suggest.请建议。 termsName0 may be 2 ,3 4 or N numbers termName0 可以是 2 ,3 4 或 N 个数字

Code:代码:

Select(self.driver.find_element_by_name("termsName0")).select_by_visible_text("Blank No Text")
Select(self.driver.find_element_by_name("termsName1")).select_by_visible_text("Blank No Text")
Select(self.driver.find_element_by_name("termsName3")).select_by_visible_text("Blank No Text")

You can use try except contract if you do not know the "N".如果您不知道“N”,您可以使用 try except contract 。

from selenium.common.exceptions import ElementNotVisibleException, WebDriverException, NoSuchElementException

try:
    i = 0
    while True:
        name = "termsName" + str(i)
        Select(self.driver.find_element_by_name(name).select_by_visible_text("Blank No Text")
        i +=1
 except (ElementNotVisibleException, WebDriverException, NoSuchElementException):
        pass

This is one way.这是一种方式。 N specifies how many times you want to loop N 指定要循环的次数

N = 4

for i in range(N):
    name = "termsName" + str(i)
    Select(self.driver.find_element_by_name(name).select_by_visible_text("Blank No Text")

Basically it takes the number of the current iteration and appends that to "termsName" .基本上它需要当前迭代的数量并将其附加到"termsName"

Above code is equivalent to上面的代码相当于

Select(self.driver.find_element_by_name("termsName0")).select_by_visible_text("Blank No Text")
Select(self.driver.find_element_by_name("termsName1")).select_by_visible_text("Blank No Text")
Select(self.driver.find_element_by_name("termsName2")).select_by_visible_text("Blank No Text")
Select(self.driver.find_element_by_name("termsName3")).select_by_visible_text("Blank No Text")

For iterating variable number of items you could try something like this为了迭代可变数量的项目,你可以尝试这样的事情

#To fetch all elements start with termsName 
element_list = firefox_driver.find_elements_by_id("termsName[0-9]*")

# below code will iterate over the all links
for i in range(len(element_list)):
        name = "termsName" + str(i)
        Select(self.driver.find_element_by_name(name).select_by_visible_text("Blank No Text")

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM