1

我编写了一个 python 脚本,从我们正在使用的一些硬件中获取一个健康状态网页。查看 HTML 和 javascript 文件,获取我想要的内容相对容易。问题是我无法结束会话并删除 cookie,以便在我的会话超时之前 Web 界面可供其他用户使用。我无法在服务器端更改任何内容。

我正在做的基本上是:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
url=mydataurl
headers={"Authorization:"username:encrytptedpassword","Cookie":"user=username; password="encryptedpassword"}
# Both Authorization and Cookie need to be set to go further
data="something"

req=urllib2.Request(url,data,headers)
connection=urllib2.urlopen(req)
response=connection.read()

# Now I have what I want in response and can work on that. 
# But the server thinks I am still active and does not let anybody else in

# So I call what is called when I press logout on the web page:

url=logouturl
headers={}
data=""
req=urllib2.Request(url,None,headers)
connection=urllib2.urlopen(req)
logoutresponse=connection.read()

#and just in case

headers={}
cj.clear()
cj.clear_session_cookies()
url="http://myserver/index.htm"
req=urllib2.Request(url,None,headers)
connection=urllib2.urlopen(req)
logoutresponse=connection.read()

connection.close()

我在此会话中删除 cookie 是否做错了什么?我也尝试关闭我已经启动的所有三个连接,但无济于事。

我可以在运行脚本的计算机上的浏览器中打开网页,然后在另一台计算机上打开后立即注销。如果我运行脚本,我必须等待几分钟才能在服务器上超时,然后才能再次登录。

当然,这可能是服务器也在做其他事情来保持会话处于活动状态,如果是这样,我可能不走运。

我更喜欢使用内置库,目前无法升级到使用 python 3。

4

1 回答 1

1

“删除” cookie 的常用方法是简单地将 cookie 的到期日期设置为过去的某个时间(许多系统可以将其设置为 time=0 应该可以工作)。我不熟悉 cookiejar,但您可能想研究这种方法。

于 2018-12-17T09:25:45.693 回答