目录

1. 简介2. Python历史3. 安装Python3.1. Python解释器4. 第一个Python程序4.1. 使用文本编辑器4.2. 输入和输出5. Python基础5.1. 数据类型和变量5.2. 字符串和编码5.3. 使用list和tuple5.4. 条件判断5.5. 模式匹配5.6. 循环5.7. 使用dict和set6. 函数6.1. 调用函数6.2. 定义函数6.3. 函数的参数6.4. 递归函数7. 高级特性7.1. 切片7.2. 迭代7.3. 列表生成式7.4. 生成器7.5. 迭代器8. 函数式编程8.1. 高阶函数8.1.1. map/reduce8.1.2. filter8.1.3. sorted8.2. 返回函数8.3. 匿名函数8.4. 装饰器8.5. 偏函数9. 模块9.1. 使用模块9.2. 安装第三方模块10. 面向对象编程10.1. 类和实例10.2. 访问限制10.3. 继承和多态10.4. 获取对象信息10.5. 实例属性和类属性11. 面向对象高级编程11.1. 使用__slots__11.2. 使用@property11.3. 多重继承11.4. 定制类11.5. 使用枚举类11.6. 使用元类12. 错误、调试和测试12.1. 错误处理12.2. 调试12.3. 单元测试12.4. 文档测试13. IO编程13.1. 文件读写13.2. StringIO和BytesIO13.3. 操作文件和目录13.4. 序列化14. 进程和线程14.1. 多进程14.2. 多线程14.3. ThreadLocal14.4. 进程 vs. 线程14.5. 分布式进程15. 正则表达式16. 常用内建模块16.1. datetime16.2. collections16.3. argparse16.4. base6416.5. struct16.6. hashlib16.7. hmac16.8. itertools16.9. contextlib16.10. urllib16.11. XML16.12. HTMLParser16.13. venv17. 常用第三方模块17.1. Pillow17.2. requests17.3. chardet17.4. psutil18. 图形界面18.1. 海龟绘图19. 网络编程19.1. TCP/IP简介19.2. TCP编程19.3. UDP编程20. 电子邮件20.1. SMTP发送邮件20.2. POP3收取邮件21. 访问数据库21.1. 使用SQLite21.2. 使用MySQL21.3. 使用SQLAlchemy22. Web开发22.1. HTTP协议简介22.2. HTML简介22.3. WSGI接口22.4. 使用Web框架22.5. 使用模板23. 异步IO23.1. 协程23.2. 使用asyncio23.3. 使用aiohttp24. FAQ25. 期末总结

16.10. urllib

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

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

from urllib import request

with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', data.decode('utf-8'))

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

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

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

from urllib import request

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

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

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

Post

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

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

from urllib import request, parse

print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
    ('username', email),
    ('password', passwd),
    ('entry', 'mweibo'),
    ('client_id', ''),
    ('savestate', '1'),
    ('ec', ''),
    ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])

req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
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')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')

with request.urlopen(req, data=login_data.encode('utf-8')) as f:
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', f.read().decode('utf-8'))

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

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

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

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

Handler

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

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

小结

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

练习

利用urllib读取JSON,然后将JSON解析为Python对象:

from urllib import request

def fetch_data(url):
    return ''

# 测试
URL = 'https://api.weatherapi.com/v1/current.json?key=b4e8f86b44654e6b86885330242207&q=Beijing&aqi=no'
data = fetch_data(URL)
print(data)
assert data['location']['name'] == 'Beijing'
print('ok')

参考源码

use_urllib.py