分享一个常用的Python模拟登陆类
代码非常简单,而且注释也很详细,这里就不多废话了
tools.py
#-*-coding:utf8-*- ''' #============================================================================= #FileName:tools.py #Desc:模拟浏览器 #Author:cosven #Email:yinshaowen241@gmail.com #HomePage:www.cosven.com #Version:0.0.1 #LastChange:2015-03-2700:59:24 #History: #============================================================================= ''' importurllib importurllib2 importcookielib classMyWeb(): """ 模拟一个浏览器 """ def__init__(self): self.header={ 'Host':'music.163.com', 'Content-Type':"application/x-www-form-urlencoded;charset=UTF-8", 'Referer':'http://music.163.com/song?id=26599525', "User-Agent":"Opera/8.0(Macintosh;PPCMacOSX;U;en)" } self.cookie=cookielib.LWPCookieJar() self.cookie_support=urllib2.HTTPCookieProcessor(self.cookie) self.opener=urllib2.build_opener(self.cookie_support, urllib2.HTTPHandler) urllib2.install_opener(self.opener) defpost(self,posturl,dictdata): """ 模拟post请求 :paramstringposturl:url地址 :paramdictdictdata:发送的数据 """ postdata=urllib.urlencode(dictdata) request=urllib2.Request(posturl,postdata,self.header) try: content=urllib2.urlopen(request) returncontent exceptException,e: print("post:"+str(e)) returnNone defget(self,url): """ 模拟get请求 :paramurl:url地址 :returncontent:常使用read的方法来读取返回数据 :rtype:instanceorNone """ request=urllib2.Request(url,None,self.header) try: content=urllib2.urlopen(request) returncontent exceptException,e: print("open:"+str(e)) returnNone if__name__=="__main__": importhashlib web=MyWeb() url='http://music.163.com/api/login/' data={ 'username':'username',#email 'password':hashlib.md5('password').hexdigest(),#password 'rememberLogin':'true' } res=web.post(url,data) printres.read() #url_add='http://music.163.com/api/playlist/manipulate/tracks' #data_add={ #'tracks':'26599525',#musicid #'pid':'16199365',#playlistid #'trackIds':'["26599525"]',#musicidstr #'op':'add'#opation #} #res_add=web.post(url_add,data_add) #printres_add.read() #完了可以试着查看自己网易云音乐相应列表歌曲
以上就是本文给大家分享的代码了,希望大家能够喜欢,也希望能够对大家学习Python有所帮助。