python登陆网页并处理网站session和cookie

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

这是一个python通过urllib直接登陆网站,并处理网站的session和cookie

import cookielib, urllib, urllib2
 
login = 'ismellbacon123@yahoo.com'
password = 'login'
 
# Enable cookie support for urllib2
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
 
# Send login/password to the site and get the session cookie
values = {'login':login, 'password':password }
data = urllib.urlencode(values)
request = urllib2.Request("http://www.imdb.com/register/login", data)
url = urlOpener.open(request)  # Our cookiejar automatically receives the cookies
page = url.read(500000)
 
# Make sure we are logged in by checking the presence of the cookie "id".
# (which is the cookie containing the session identifier.)
if not 'id' in [cookie.name for cookie in cookiejar]:
    raise ValueError, "Login failed with login=%s, password=%s" % (login,password)
 
print "We are logged in !"
 
# Make another request with our session cookie
# (Our urlOpener automatically uses cookies from our cookiejar)
url = urlOpener.open('http://imdb.com/find?s=all&q=grave')
page = url.read(200000)

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java图片居中裁剪代码

下一篇: IOS之同步请求、异步请求、GET请求、POST请求