分享一个常用的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-27 00:59:24
# history:
# =============================================================================
”’
import urllib
import urllib2
import cookielib
class myweb():
“””
模拟一个浏览器
“””
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?,
“user-agent”: “opera/8.0 (macintosh; ppc mac os x; 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)
def post(self, posturl, dictdata):
“””
模拟post请求
:param string posturl: url地址
:param dict dictdata: 发送的数据
“””
postdata = urllib.urlencode(dictdata)
request = urllib2.request(posturl, postdata, self.header)
try:
content = urllib2.urlopen(request)
return content
except exception, e:
print (“post:” + str(e))
return none
def get(self, url):
“””
模拟get请求
:param url: url地址
:return content: 常使用read的方法来读取返回数据
:rtype : instance or none
“””
request = urllib2.request(url, none, self.header)
try:
content = urllib2.urlopen(request)
return content
except exception, e:
print (“open:” + str(e))
return none
if __name__ == “__main__”:
import hashlib
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)
print res.read()
# url_add = ‘http://music.163.com/api/playlist/manipulate/tracks’
# data_add = {
# ‘tracks’: ‘26599525’, # music id
# ‘pid’: ‘16199365’, # playlist id
# ‘trackids’: ‘[“26599525”]’, # music id str
# ‘op’: ‘add’ # opation
# }
# res_add = web.post(url_add, data_add)
# print res_add.read()
# 完了可以试着查看自己网易云音乐相应列表歌曲

以上就是本文给大家分享的代码了,希望大家能够喜欢,也希望能够对大家学习python有所帮助。

Posted in 未分类

发表评论