urllib

urllib提供了一系列用于操作URL的功能。

Get

urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:

例如,对豆瓣的一个URLhttps://api.douban.com/v2/book/2129650进行抓取,并返回响应:

  1. from urllib import request
  2. with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
  3. data = f.read()
  4. print('Status:', f.status, f.reason)
  5. for k, v in f.getheaders():
  6. print('%s: %s' % (k, v))
  7. print('Data:', data.decode('utf-8'))

可以看到HTTP响应的头和JSON数据:

  1. Status: 200 OK
  2. Server: nginx
  3. Date: Tue, 26 May 2015 10:02:27 GMT
  4. Content-Type: application/json; charset=utf-8
  5. Content-Length: 2049
  6. Connection: close
  7. Expires: Sun, 1 Jan 2006 01:00:00 GMT
  8. Pragma: no-cache
  9. Cache-Control: must-revalidate, no-cache, private
  10. X-DAE-Node: pidl1
  11. Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰编著"],"pubdate":"2007-6","tags":[{"count":20,"name":"spring","title":"spring"}...}

如果我们要想模拟浏览器发送GET请求,就需要使用Request对象,通过往Request对象添加HTTP头,我们就可以把请求伪装成浏览器。例如,模拟iPhone 6去请求豆瓣首页:

  1. from urllib import request
  2. req = request.Request('http://www.douban.com/')
  3. 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')
  4. with request.urlopen(req) as f:
  5. print('Status:', f.status, f.reason)
  6. for k, v in f.getheaders():
  7. print('%s: %s' % (k, v))
  8. print('Data:', f.read().decode('utf-8'))

这样豆瓣会返回适合iPhone的移动版网页:

  1. ...
  2. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
  3. <meta name="format-detection" content="telephone=no">
  4. <link rel="apple-touch-icon" sizes="57x57" href="http://img4.douban.com/pics/cardkit/launcher/57.png" />
  5. ...

Post

如果要以POST发送一个请求,只需要把参数data以bytes形式传入。

我们模拟一个微博登录,先读取登录的邮箱和口令,然后按照weibo.cn的登录页的格式以username=xxx&password=xxx的编码传入:

  1. from urllib import request, parse
  2. print('Login to weibo.cn...')
  3. email = input('Email: ')
  4. passwd = input('Password: ')
  5. login_data = parse.urlencode([
  6. ('username', email),
  7. ('password', passwd),
  8. ('entry', 'mweibo'),
  9. ('client_id', ''),
  10. ('savestate', '1'),
  11. ('ec', ''),
  12. ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
  13. ])
  14. req = request.Request('https://passport.weibo.cn/sso/login')
  15. req.add_header('Origin', 'https://passport.weibo.cn')
  16. 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')
  17. req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
  18. with request.urlopen(req, data=login_data.encode('utf-8')) as f:
  19. print('Status:', f.status, f.reason)
  20. for k, v in f.getheaders():
  21. print('%s: %s' % (k, v))
  22. print('Data:', f.read().decode('utf-8'))

如果登录成功,我们获得的响应如下:

  1. Status: 200 OK
  2. Server: nginx/1.2.0
  3. ...
  4. Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
  5. ...
  6. Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}

如果登录失败,我们获得的响应如下:

  1. ...
  2. Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"example@python.org","errline":536}}

Handler

如果还需要更复杂的控制,比如通过一个Proxy去访问网站,我们需要利用ProxyHandler来处理,示例代码如下:

  1. proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
  2. proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
  3. proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
  4. opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
  5. with opener.open('http://www.example.com/login.html') as f:
  6. pass

小结

urllib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。

练习

利用urllib读取XML,将XML一节的数据由硬编码改为由urllib获取:

  1. from urllib import request, parse
  2. def fetch_xml(url):
  3. pass
  4. # 测试
  5. print(fetch_xml('http://weather.yahooapis.com/forecastrss?u=c&w=2151330'))

参考源码

use_urllib.py

原文: https://wizardforcel.gitbooks.io/liaoxuefeng/content/py3/79.html