gpt4 book ai didi

python - 如何从以前保存的 splinter 实例中在 splinter 中设置 cookie?

转载 作者:行者123 更新时间:2023-12-05 07:52:25 25 4
gpt4 key购买 nike

所以我使用 splinter 登录到一个站点,然后我在登录后抓取 cookie,然后将其保存为 pickled 对象以备后用。

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

当我查看屏幕截图时,用户只是在访问网站,并未处于登录状态。

最佳答案

我遇到了类似的情况,对我来说,在添加 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 .

关于python - 如何从以前保存的 splinter 实例中在 splinter 中设置 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com