1. urllib
    2. 阅读: 201907
    3. urllib提供了一系列用于操作URL的功能。
    4. Get
    5. urllibrequest模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:
    6. 例如,对豆瓣的一个URLhttps://api.douban.com/v2/book/2129650进行抓取,并返回响应:
    7. from urllib import request
    8. with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
    9. data = f.read()
    10. print('Status:', f.status, f.reason)
    11. for k, v in f.getheaders():
    12. print('%s: %s' % (k, v))
    13. print('Data:', data.decode('utf-8'))
    14. 可以看到HTTP响应的头和JSON数据:
    15. Status: 200 OK
    16. Server: nginx
    17. Date: Tue, 26 May 2015 10:02:27 GMT
    18. Content-Type: application/json; charset=utf-8
    19. Content-Length: 2049
    20. Connection: close
    21. Expires: Sun, 1 Jan 2006 01:00:00 GMT
    22. Pragma: no-cache
    23. Cache-Control: must-revalidate, no-cache, private
    24. X-DAE-Node: pidl1
    25. Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰编著"],"pubdate":"2007-6",...}
    26. 如果我们要想模拟浏览器发送GET请求,就需要使用Request对象,通过往Request对象添加HTTP头,我们就可以把请求伪装成浏览器。例如,模拟iPhone 6去请求豆瓣首页:
    27. from urllib import request
    28. req = request.Request('http://www.douban.com/')
    29. req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    30. with request.urlopen(req) as f:
    31. print('Status:', f.status, f.reason)
    32. for k, v in f.getheaders():
    33. print('%s: %s' % (k, v))
    34. print('Data:', f.read().decode('utf-8'))
    35. 这样豆瓣会返回适合iPhone的移动版网页:
    36. ...
    37. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    38. <meta name="format-detection" content="telephone=no">
    39. <link rel="apple-touch-icon" sizes="57x57" href="http://img4.douban.com/pics/cardkit/launcher/57.png" />
    40. ...
    41. Post
    42. 如果要以POST发送一个请求,只需要把参数databytes形式传入。
    43. 我们模拟一个微博登录,先读取登录的邮箱和口令,然后按照weibo.cn的登录页的格式以username=xxx&password=xxx的编码传入:
    44. from urllib import request, parse
    45. print('Login to weibo.cn...')
    46. email = input('Email: ')
    47. passwd = input('Password: ')
    48. login_data = parse.urlencode([
    49. ('username', email),
    50. ('password', passwd),
    51. ('entry', 'mweibo'),
    52. ('client_id', ''),
    53. ('savestate', '1'),
    54. ('ec', ''),
    55. ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
    56. ])
    57. req = request.Request('https://passport.weibo.cn/sso/login')
    58. req.add_header('Origin', 'https://passport.weibo.cn')
    59. req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    60. req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
    61. with request.urlopen(req, data=login_data.encode('utf-8')) as f:
    62. print('Status:', f.status, f.reason)
    63. for k, v in f.getheaders():
    64. print('%s: %s' % (k, v))
    65. print('Data:', f.read().decode('utf-8'))
    66. 如果登录成功,我们获得的响应如下:
    67. Status: 200 OK
    68. Server: nginx/1.2.0
    69. ...
    70. Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
    71. ...
    72. Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}
    73. 如果登录失败,我们获得的响应如下:
    74. ...
    75. Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"example@python.org","errline":536}}
    76. Handler
    77. 如果还需要更复杂的控制,比如通过一个Proxy去访问网站,我们需要利用ProxyHandler来处理,示例代码如下:
    78. proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
    79. proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
    80. proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
    81. opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
    82. with opener.open('http://www.example.com/login.html') as f:
    83. pass
    84. 小结
    85. urllib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。
    86. 练习
    87. 利用urllib读取JSON,然后将JSON解析为Python对象:
    88. # -*- coding: utf-8 -*-
    89. from urllib import request
    90. def fetch_data(url):
    91. return ''
    92. # 测试
    93. URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json'
    94. data = fetch_data(URL)
    95. print(data)
    96. assert data['query']['results']['channel']['location']['city'] == 'Beijing'
    97. print('ok')
    98. Run
    99. 参考源码
    100. use_urllib.py