代碼非常簡(jiǎn)單,而且注釋也很詳細(xì),這里就不多廢話了
tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
# -*- coding:utf8 -*- ''' # ============================================================================= # FileName: tools.py # Desc: 模擬瀏覽器 # Author: cosven # Email: [email protected] # HomePage: www.cosven.com # Version: 0.0.1 # LastChange: 2015-03-27 00:59:24 # History: # ============================================================================= ''' import urllib import urllib2 import cookielib class MyWeb(): """ 模擬一個(gè)瀏覽器 """ 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): """ 模擬post請(qǐng)求 :param string posturl: url地址 :param dict dictdata: 發(fā)送的數(shù)據(jù) """ 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請(qǐng)求 :param url: url地址 :return content: 常使用read的方法來讀取返回?cái)?shù)據(jù) :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() # 完了可以試著查看自己網(wǎng)易云音樂相應(yīng)列表歌曲 |
以上就是本文給大家分享的代碼了,希望大家能夠喜歡,也希望能夠?qū)Υ蠹覍W(xué)習(xí)Python有所幫助。