所以我使用splinter登录到一个站点,然后我在登录后抓取cookie,然后将其保存为pickle对象供以后使用。
def save_cookie(username, password):
browser = Browser()
browser.visit("https://somesite.com")
browser.fill('username', username)
browser.fill('password', password)
login_button = browser.find_by_xpath('the_login_button_x_path')
login_button.click()
# make a file and save the pickled object.
file_Name = "the_cookie"
fileObject = open(file_Name,'wb')
pickle.dump(browser.cookies.all(verbose=True) ,fileObject)
fileObject.close()
# so file is saved.
# I take screen shot so that I know that the user is logged in.
browser.driver.save_screenshot('screenshot.png')
所以我希望能够保存那些cookie数据,以便稍后在另一个splinter Browser()实例中再次使用它。这将允许我登录一次而不是每次我想测试需要登录状态的页面时登录。
def visit_site_as_logged_in_user():
browser = Browser()
#open the previously pickled cookies object and load it
the_previously_saved_cookies = pickle.load( open( "the_cookie", "rb"))
#set the cookies on this new browser instance
browser.cookies.add(the_previously_saved_cookies)
#visit the site
browser.visit("https://somesite.com")
# I take screen shot so that I know that the user is logged in.
browser.driver.save_screenshot('screenshot.png')
所以我希望用户访问该站点并处于登录状态,因为我从第一个实例获取完全相同的cookie并将其应用于新实例。我可能误解了splinter如何处理cookie。该文档不是很具描述性。 http://splinter.readthedocs.org/en/latest/cookies.html
当我查看屏幕截图时,用户只是访问该网站并且未处于登录状态。
答案 0 :(得分:0)
我有类似的情况,对我来说,它是通过在添加cookie后访问内部网站来解决的。
def visit_site_as_logged_in_user():
browser = Browser()
#open the previously pickled cookies object and load it
the_previously_saved_cookies = pickle.load( open( "the_cookie", "rb"))
#set the cookies on this new browser instance
browser.visit("https://somesite.com") # see below
browser.cookies.add(the_previously_saved_cookies)
#visit the site
browser.visit("https://somesite.com/internal")
# I take screen shot so that I know that the user is logged in.
browser.driver.save_screenshot('screenshot.png')
这对我有用,可能取决于网站,但通过此设置我不必再次填写登录表单。此外,我必须访问基站以设置cookie,请参阅Unable to add a cookie using Selenium & Splinter。