Python For Loop打印语句

时间:2020-03-05 15:47:44

标签: python selenium loops printing

from selenium import webdriver
import time


def test_setup():
    global driver
    driver = webdriver.Chrome(executable_path="C:/ChromeDriver/chromedriver.exe")
    driver.implicitly_wait(5)
    driver.maximize_window()
    time.sleep(5)


    siteUrls = ["https://www.espncricinfo.com/", "https://www.t20worldcup.com/","https://www.iplt20.com/"]

    for url in siteUrls:
        openSite(url)

def openSite(siteUrl):
    driver.get(siteUrl)
    time.sleep(5)
    print("ESPN website is launched successfully")


def test_teardown():
    driver.close()
    driver.quit()

以上是我的代码,它运行得非常好,我的问题是,它为所有3个URL输出与输出相同的语句,但我希望它打印3个不同的语句

例如-我想要下面的预期输出

ESPN website is launched successfully
IPL website is launched successfully
world-cup site is launched successfully

But, currently I get output as below ( same statement repeated 3 times)
ESPN website is launched successfully
ESPN website is launched successfully
ESPN website is launched successfully

4 个答案:

答案 0 :(得分:1)

您需要提供一个适当的名称作为openSite的第二个参数。例如,

    ...

    siteUrls = [
        ("ESPN", "https://www.espncricinfo.com/"),
        ("world-cup", "https://www.t20worldcup.com/"),
        ("IPL", "https://www.iplt20.com/")
    ]

    for name, url in siteUrls:
        openSite(name, url)


def openSite(name, siteUrl):
    driver.get(siteUrl)
    time.sleep(5)
    print(f"{name} website is launched successfully")

答案 1 :(得分:1)

您的打印语句中没有任何参数。这就是为什么您总是获得相同的输出的原因。这是一个可能的解决方案:

def openSite(siteUrl):
    driver.get(siteUrl)
    time.sleep(5)
    print(siteUrl, "is launched successfully")

答案 2 :(得分:1)

def openSite(siteUrl):
    driver.get(siteUrl)
    time.sleep(5)

    # Split the url at the period and get index 1 from list that contains site name
    site_name = siteUrl.split('.')[1]
    print(site_name + " website is launched successfully")

#output:
#>> espncricinfo website is launched successfully
#>> t20worldcup website is launched successfully
#>> iplt20website is launched successfully

答案 3 :(得分:0)

您需要将某些内容传递给打印语句。例如

print(f"{siteUrl} launched")