
requests是一个Python第三方库,处理URL资源特别方便。
安装requests
如果安装了Anaconda,requests就已经可用了。否则,需要在命令行下通过pip安装:
如果遇到Permission denied安装失败,请加上sudo重试。
使用requests
要通过GET访问一个页面,只需要几行代码:
1 2 3 4 5 6 7 | >>> import requests
>>> r = requests.get('https://www.douban.com/') # 豆瓣首页
>>> r.status_code
200
>>> r.text
r.text
'<!DOCTYPE HTML>\n< html >\n< head >\n<meta name="description" content="提供图书、电影、音乐唱片的推荐、评论和...'
|
(更多内容,请点击python学习网)
对于带参数的URL,传入一个dict作为params参数:
1 2 3 4 5 6 | >>> r = requests.get('https://www.douban.com/search', params={'q': 'python', 'cat': '1001'})
>>> r.url # 实际请求的URL
'https://www.douban.com/search?q=python&cat=1001'
requests自动检测编码,可以使用encoding属性查看:
>>> r.encoding
'utf-8'
|
无论响应是文本还是二进制内容,我们都可以用content属性获得bytes对象:
1 2 | >>> r.content
b'<!DOCTYPE html>\n< html >\n< head >\n< meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" >\n...'
|
requests的方便之处还在于,对于特定类型的响应,例如JSON,可以直接获取:
1 2 3 4 5 | >>> r = requests.get('
where%20woeid%
20%3D%202151330&format=json')
>>> r.json()
{'query': {'count': 1, 'created': '2017-11-17T07:14:12Z', ...
|
需要传入HTTP Header时,我们传入一个dict作为headers参数:
1 2 3 4 | >>> r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like
Mac OS X) AppleWebKit'})
>>> r.text
'<!DOCTYPE html>\n< html >\n< head >\n< meta charset = "UTF-8" >\n < title >豆瓣(手机版)</ title >...'
|