簡體   English   中英

Python - while 循環,調用變量

[英]Python - while loop, call variable

如何在下面的腳本末尾調用n 我不斷收到錯誤“消息:javascript 錯誤:n 未定義”

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

在這些行中,“tab”應該在每個周期遞增,例如 tab1、tab2、tab3...tab10:

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

謝謝

試試這個代碼:(通過替換你現有的代碼)

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

示例:

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

一旦你得到這個,你可以將它與你的 sselenium 代碼集成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM