Share a common Python mock login class
- 2020-04-02 14:45:12
- OfStack
The code is very simple, and the comments are very detailed, so there's no more nonsense here
The tools. Py
# -*- coding:utf8 -*-
'''
# =============================================================================
# FileName: tools.py
# Desc: Mock browser
# 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():
"""
Simulate a browser
"""
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; 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):
"""
simulation post request
:param string posturl: url address
:param dict dictdata: Data sent
"""
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):
"""
simulation get request
:param url: url address
:return content: Often use read Method to read the returned data
: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()
# End can try to view their own netease cloud music corresponding list of songs
The above is the article to share the code, I hope you can like, but also hope to help you learn Python.