英文:
Avoid login each time i run script in Selenium python
问题
我正在使用Selenium Python自动化一个网站。当我使用driver.get()
访问我的网站时,它会跳转到微软登录界面,登录后需要进行双因素身份验证,然后才能打开实际的网站。
现在的问题是,当我在我的代码中添加新脚本并希望检查它是否正常工作时,我必须运行上述所有登录步骤,然后运行新的代码。
这真的非常耗时。我需要建议,以避免每次都要登录,只是为了检查我的下一行代码是否正常工作或不。
感谢您的帮助。
英文:
I am automating a website using selenium pyhton. When I go to my website using driver.get(), it goes to microsoft login screen and after login it require two factor authentication and after that it opens the actual website.
Now the problem is when i add new script in my code and i want to check if it is working right, I have to run all the above steps for login and then run the new code.
It is really time consuming. I need suggestions for avoid login each time just to check if my next lines of code are working or not.
I'll appreciate your help.
答案1
得分: 3
Cookies
为了避免登录过程,您有两个选项,第一个选项涉及将 cookies 保存在文件中,并在需要时加载它。
url = 'https://www.microsoft.com'
driver.get(url)
# 手动输入用户名和密码
import pickle
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))
driver.quit()
然后重新启动 webdriver 并运行:
driver.get(url)
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
用户配置文件
另外,您可以加载一个已经登录的用户配置文件。这里 提供了关于如何在 Chrome 中创建用户配置文件的逐步教程。
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\username\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument("profile-directory=Profile 2")
driver = webdriver.Chrome(..., options=options)
driver.get(url)
英文:
Cookies
To avoid the login process you have two options, the first one involves saving cookies in a file and loading it when necessary.
url = 'https://www.microsoft.com'
driver.get(url)
# manually enter username and password
import pickle
pickle.dump(driver.get_cookies(), open("cookies.pkl","wb"))
driver.quit()
then restart the webdriver and run
driver.get(url)
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
User profile
Alternatively, you can load a user profile where you are already logged in. Here you find a step by step tutorial on how to create a user profile in Chrome.
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\username\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument("profile-directory=Profile 2")
driver = webdriver.Chrome(..., options=options)
driver.get(url)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论