我正在尝试创建一个小脚本,该脚本将在后台运行并检查论坛上的新消息(使用 phpBB3)。由于许多子论坛需要登录用户的权限才能查看,我创建了一个脚本,该脚本将向服务器发送后请求以首先登录。
该脚本当前成功登录,并收到一条欢迎消息,告诉我我已登录。但是当我访问新页面时,脚本似乎忘记了我已登录并且我的会话cookie已更改。
这是我创建的一些小测试代码,它给了我错误:
import urllib, urllib2, cookielib, re, time
username = "username"
password = "password"
loginsite = "http://www.mydomain.com/ucp.php?mode=login"
ok_tekst = "You have been successfully logged in."
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'password' : password,
"autologin" : "on", 'login' : 'Login'})
resp = opener.open(loginsite, login_data)
if ok_tekst in resp.read():
print "Login successfull"
print "Cookies are:"
for cookie in cj:
print cookie
post_site = "http://www.mydomain.com/"
ok_tekst = "Logout [ " + username + " ]"
resp = opener.open(post_site)
readHTML = resp.read()
if ok_tekst not in readHTML:
print ""
print "Unsuccessfull, I am now logged out?!"
print "Cookies are now:"
for cookie in cj:
print cookie
这会产生以下输出,其中还显示了不同 cookie 的值:
>> python test.py
Login successfull
Cookies are:
<Cookie phpbb3_pwsle_k=b3fe944b89bfbce2 for .mydomain.com/>
<Cookie phpbb3_pwsle_sid=318b3ace3d52409fb5e1eef87433fbdb for .mydomain.com/>
<Cookie phpbb3_pwsle_u=419 for .mydomain.com/>
Unsuccessfull, I am now logged out?!
Cookies are now:
<Cookie phpbb3_pwsle_k= for .mydomain.com/>
<Cookie phpbb3_pwsle_sid=719520cd3a16526d6da4fa2fbdfe40f4 for .mydomain.com/>
<Cookie phpbb3_pwsle_u=1 for .mydomain.com/>