【问题标题】:Python For Loop Print statementPython For 循环打印语句
【发布时间】:2020-06-18 07:28:48
【问题描述】:
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

【问题讨论】:

  • 您的打印语句中没有任何参数。
  • print(siteUrl + " is launched successfully")print(f"{siteUrl} is launched successfully") 怎么样

标签: python selenium loops printing


【解决方案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")

【讨论】:

  • 您是否重新定义了siteUrls,如答案所示?
  • Hey chepner - 非常抱歉,是的,您的代码也可以正常工作……我的错,我执行时遗漏了一些东西
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    print(f"{siteUrl} launched")
    

    【讨论】:

      【解决方案4】:
      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
      

      【讨论】: