urllib2 登录 login

#!/usr/bin/python
#coding=utf-8


import urllib
import urllib2
import cookielib

def post(url, data):

data = urllib.urlencode(data)   #将dict转换为http传递时数据  username=name&password=myword

hds = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'}  #header,模仿浏览器

req = urllib2.Request(url, data, headers=hds) #后加参数data,即可成为post请求, req.get_method()可知,此处headers不加也可 


#对于提交json

#son_data = json.dumps(post_data)

#req = urllib2.Request(url, json_data)

#req.add_header('Context-Type', 'application/json')   #一定要加

#urllib2.urlopen(req)  #不需要cookie时,直接这样就提交了 


#enable cookie

cj = cookielib.CookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))  
response = opener.open(req)  #此步骤为登录,以后就可以用opner 来打开别的页面,且状态是登录后的装态
return (response.read(), opener)



def main():
posturl = "http://www.baidu.com/login"
data = { 'password':'mypass', 'autologin':'1', 'username':'my_username',}
html, opener = post(posturl, data)
opener .open(new_url)  #用opener直接打开新的url

if __name__ == '__main__':
main()

你可能感兴趣的:(python)