简体   繁体   中英

Generic code for clicking web element from a list in Python:

Here is my code in Java that I want to convert in Python:

public static void clickElementFromList(String ListObject, String strname) 
{
    List<WebElement> wbeElement;

    wbeElement = Util.findElements(ListObject);

    for (int cnt = 0; cnt < wbeElement.size(); cnt++) 
    {
        if (wbeElement.get(cnt).getText().trim().contentEquals(strname)) 
        {
            wbeElement.get(cnt).click();
            break;
        }
    }

}

//listobj is the web element. //strname is the displayed text in the application

First of all we are not translators..

If you want to translate java code to python you have to translate it manually. It looks like there are some tools out eg java2python but the author states

The generated Python code is not guaranteed to run, nor is guaranteed to be syntactically valid Python.

If you simply want to use a java library in a application that you want to write in python you could give jython a try.

But as per your question and requirement to give you example/sample or a hint..

First find all elements of list according to your condition by!

from selenium import webdriver

browser = webdriver.Chrome()
browser.get(url)
# here find method will have to modified according to your condition of getting webElements
list = browser.find()

Then as per your requirement of method try something like this:

def clickElementFromList(list_object, strname):
    for name in list_object:
        text = name.text
        if text is not None:
            if text == strname:
                name.click()
                break

Then call function:

clickElementFromList(your list here, strname here)

Hope this will help you! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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