首页 > 解决方案 > 如何将 url 作为用户输入传递以通过 Selenium 和 Python 调用?

问题描述

每次我运行我的脚本时,我希望它使用 input() 询问我的目标 url 是什么,以便它可以将其存储为变量并在函数中使用它,但每次我输入 url 时,脚本都不会继续并按下enter 导致它在我的默认浏览器上将 url 作为选项卡而不是新的 chrome 对象打开。

def function1(targeturl):
 driver = webdriver.Chrome()
 driver.get(targeturl)

print('What is the website?')
webPage = input()
function1(webPage)

我不确定 IDE 是否重要,但我正在使用 Pycharm。在它询问我之后,我将复制并粘贴 url,当我按下回车键时,它将打开 url 而不是继续脚本

标签: pythonseleniumselenium-webdriverwebdriveruser-input

解决方案


要调用作为用户输入的url ,您可以使用该函数。input()

这是您自己的程序,带有一些简单的增强功能,它将从用户那里一一接受 3 个url并导航到相应的url

  • 代码块:

    from selenium import webdriver
    
    def function1(targeturl):
        driver.get(targeturl)
        # perform your taks here
    
    driver = webdriver.Chrome()
    for i in range(3):
        webPage = input("What is the website url?(Press enter at the end to continue):")
        function1(webPage)
    driver.quit()
    
  • 控制台输出:

    What is the website url?(Press enter at the end to continue):http://www.google.com
    What is the website url?(Press enter at the end to continue):http://www.facebook.com
    What is the website url?(Press enter at the end to continue):http://www.gmail.com
    

推荐阅读