Home > Back-end >  Running a "for" loop in JavaScript through Python-Selenium?
Running a "for" loop in JavaScript through Python-Selenium?

Time:01-02

I use Javascript to collate data from an HTML page via Selenium; however, I cannot run the Javascript portion from my computer via Selenium/py cause Python only offers the driver.execute_script('string of a script'), whereas I have a multi-line for loop which won't execute with these commands.

The loop:

for (let i = 0; i < Values.length; i  ) {
    if (Values[i].getAttribute('automation-id') === 'contact-wealth-manager') {
        ele = Values[i]
    }
}

As you can test, this won't work with the standard "driver.execute_script("let value = '';")

CodePudding user response:

To execute the multiline loop Javascript you need to pass the script as an argument to execute_script() method as follows:

driver.execute_script("""
    for (let i = 0; i < Values.length; i  ) {
        if (Values[i].getAttribute('automation-id') === 'contact-wealth-manager') {
            ele = Values[i]
        }
    }
""")
  • Related