问题
Every time I run my script I want it to ask me what is the targeted url using input() so it can store it as a variable and use it in a function but every time I input the url the script won't continue and pressing enter causes it to open the url on my default browser as a tab instead of a new chrome object.
def function1(targeturl):
driver = webdriver.Chrome()
driver.get(targeturl)
print('What is the website?')
webPage = input()
function1(webPage)
I'm not sure whether the IDE is important but I'm using Pycharm. I will copy and paste the url in after it asks me and when I press enter it will open the url instead of continuing the script
回答1:
To invoke a url taken as user input you can use the input()
function.
Here is your own program with some simple enhancements which will accept 3 urls one by one from the user and navigate to the respective urls:
Code Block:
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()
Console Output:
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
回答2:
I'm not sure to understand exactly what you want to do but the script stop running because all actions are done.
Like Selenium Doc say "The driver.get method will navigate to a page given by the URL."
For example, you can add this to your function (return page title, some actions and then quit the driver):
print browser.title
'''
Make some actions
'''
browser.quit()
回答3:
If you do like this what happens? assign "targeturl" as a global variable first.
targeturl = "xxxx"
def function1(targeturl):
driver = webdriver.Chrome()
driver.get(targeturl)
print('What is the website?')
webPage = input()
function1(webPage)
来源:https://stackoverflow.com/questions/52067414/how-to-pass-urls-as-user-input-to-invoke-through-selenium-and-python