简体   繁体   中英

Python - while loop, call variable

How can I call n at the end of the script below? I keep getting the error " Message: javascript error: n is not defined"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.common.exceptions import StaleElementReferenceException

driver=webdriver.Chrome()
usr="username"
psw="pass"


n = 1
while n < 10:
    url_list = ['url 1', 'url 2', 'url 3' 'url 10']

    for url in url_list:

                    driver.get('https://%s/' %(url))

                    time.sleep(2)

                    driver.find_element_by_xpath("//input[@name='user']").send_keys(username)
                    driver.find_element_by_xpath("//input[@name='password']").send_keys(pass)
                    driver.find_element_by_id("loginButton").click()

                    driver.execute_script("window.open('about:blank', 'tabn');")
                    driver.switch_to.window("tabn",)
                    n = n + 1

In these lines "tab" should increment every cycle, like tab1, tab2, tab3...tab10:

                driver.execute_script("window.open('about:blank', '**tabn**');")
                driver.switch_to.window("**tabn**",)
                n = n + 1 

Thanks

Try this Code:(By replacing with your existing code)

driver.execute_script("window.open('about:blank', 'tab{}');".format(n))
driver.switch_to.window("tab{}".format(n),)
n = n + 1 

Sample Example:

for n in range(5):
    print("window.open('about:blank', 'tab{}');".format(n))
    print("tab{}".format(n),)
    n = n + 1 

Output:

window.open('about:blank', 'tab0');
tab0
window.open('about:blank', 'tab1');
tab1
window.open('about:blank', 'tab2');
tab2
window.open('about:blank', 'tab3');
tab3
window.open('about:blank', 'tab4');
tab4

Once you get this you can integrate it with your sselenium Code.

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