上篇文章已经介绍了urllib库的基本使用,本篇博客介绍requests库的基本使用,爬虫极力推荐requests,看完你就明白辽~。
学习之前推荐一个非常好的http测试网站:http://httpbin.org,提供非常非常完善的接口调试、测试功能~
Python里默认是没有requests库滴,安装完Python需要手动安装requests库:
pip install requests
访问baidu,获取一些基本信息:
import requests
#打开网页获取响应
response = requests.get("https://www.baidu.com")
#打印响应类型
print('response:',type(response))
#打印状态码
print('status_code:',response.status_code)
#打印字符串形式的json响应体的类型
print(type(response.text))
#打印字符串形式的响应体
print('text:',response.text)
打印cookie
print('cookie:',response.cookies)
print('二进制content:',response.content)
print('content:',response.content.decode("utf-8"))
ps:response.text是获取字符串形式的网页内容,但是由于编码问题,很容易乱码,所以还可以使用response.content以二进制形式获取,然后使用decode方法进行转码。
其实使用requset.text避免乱码的方式还有一个,就是发出请求后,获取内容之前使用response.encoding属性来改变编码,例如:
response =requests.get("http://www.baidu.com")
#设置响应内容的编码方式为utf-8
response.encoding="utf-8"
print(response.text)
requests支持http的各种请求,比如:
GET: 请求指定的页面信息,并返回实体主体。
HEAD: 只请求页面的首部。
POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
DELETE: 请求服务器删除指定的页面。
OPTIONS: 允许客户端查看服务器的性能。
1.最基本的get请求
1).一个带参数的get请求:
import requests
#将参数写在字典里,通过params传入,params接受字典或序列
data = {
"name": "hanson",
"age": 24
}
#发出一个get请求,获得响应
response = requests.get("http://httpbin.org/get", params=data)
#打印url
print(response.url)
#打印响应内容
print(response.text)
结果为:
url:http://httpbin.org/get?name=hanson&age=24
text:{
"args": {
"age": "24",
"name": "hanson"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"origin": "124.74.47.82, 124.74.47.82",
"url": "https://httpbin.org/get?name=hanson&age=24"
}
2).响应json的解析
示例:
import requests
import json
#发出一个get请求
response = requests.get("http://httpbin.org/get")
#text响应类型
print(type(response.text))
#直接解析响应json(成字典)
print(response.json())
#获取响应内容后json进行解析(成字典)
print(json.loads(response.text))
#直接解析后的相应内容类型
print(type(response.json()))
控制台打印结果:
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '124.74.47.82', 'url': 'http://httpbin.org/get'}
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '124.74.47.82', 'url': 'http://httpbin.org/get'}
发现其实requests里的json方法就是封装了json.loads方法,非常奈斯~
3).添加头信息headers
和urllib模块一样,某些网站是无法直接访问的,访问知乎:
import requests
response =requests.get("https://www.zhihu.com")
print(response.text)
打印如下错误:
400 Bad Request
400 Bad Request
openresty
我们需要为之添加头部信息:
ps:chrome查看头部信息:谷歌浏览器里输入chrome://version,就可以看到用户代理
部分结果:
Google Chrome | 72.0.3626.96 (正式版本) (64 位) |
修订版本 | 84098ee7ef8622a9defc2ef043cd8930b617b10e-refs/branch-heads/3626@{#836} |
操作系统 | Linux |
JavaScript | V8 7.2.502.25 |
Flash | 32.0.0.142 /home/hanson/.config/google-chrome/PepperFlash/32.0.0.142/libpepflashplayer.so |
用户代理 | Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36 |
命令行 | /usr/bin/google-chrome-stable --flag-switches-begin --flag-switches-end |
添加头信息后重新访问:
import requests
#添加头部信息
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
#发送请求
response = requests.get("https://www.zhihu.com", headers=headers)
#打印响应
print(response.text)
2.最基本的post请求
1).发送个带参的post试试
和get请求类似,带参的请求写在字典里携带,不过post是由data参数携带:
import requests
#参数写在字典里
data = {
"name": "hason",
"age": 23
}
#请求时将字典参数赋给data参数
response = requests.post("http://httpbin.org/post", data=data)
#打印响应
print(response.text)
打印结果:
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "23",
"name": "zhaofan"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "19",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "124.74.47.82, 124.74.47.82",
"url": "https://httpbin.org/post"
}
一下子看到这么多响应有点萌,嘎哈的呢?请看响应的获取~
2).响应
可以通过response响应获得很多属性:
import requests
response = requests.get("http://www.baidu.com")
#响应状态码
print(type(response.status_code), response.status_code)
#响应头信息
print(type(response.headers), response.headers)
#cookie
print(type(response.cookies), response.cookies)
#url
print(type(response.url), response.url)
#网络 响应历程
print(type(response.history), response.history)
打印结果:
200
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 18 Feb 2019 08:37:19 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
]>
http://www.baidu.com/
[]
补充:requests的状态码判断:
Requests还附带了一个内置的状态码查询对象
主要有如下内容:
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
Redirection.重定向
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
Client Error.客户端错误
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
Server Error.服务端错误
500: ('internal_server_error', 'server_error', '/o\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
1.文件上传
需要用到请求参数里的file参数:
import requests
#rb,以只读的方式打开二进制文件
files = {"files": open("git.jpeg", "rb")}
#发送post请求携带文件
response = requests.post("http://httpbin.org/post", files=files)
#响应内容
print(response.text)
响应结果:
{
"args": {},
"data": "",
"files": {
"files": ""
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "145",
"Content-Type": "multipart/form-data; boundary=75c9d62b8f1248a9b6a89741143836b5",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "124.74.47.82, 124.74.47.82",
"url": "https://httpbin.org/post"
}
2.获取cookie
import requests
#发送请求
response = requests.get("http://www.baidu.com")
#打印cookie
print(response.cookies)
for key, value in response.cookies.items():
print(key + "=" + value)
3.session会话维持
会话对象requests.Session能够跨请求地保持某些参数,比如cookies,即在同一个Session实例发出的所有请求都保持同一个cookies,而requests模块每次会自动处理cookies,这样就很方便地处理登录时的cookies问题。
import requests
#创建session对象
s = requests.Session()
#使用session访问并设置number参数
s.get("http://httpbin.org/cookies/set/number/123456")
#session对象再次访问,获取响应内容
response = s.get("http://httpbin.org/cookies")
print(response.text)
4.证书验证
现在的很多网站都是https的方式访问,所以这个时候就涉及到证书的问题
例如访问12306:
import requests
response = requests.get("https:/www.12306.cn")
print(response.status_code)
会报错,证书错误
解决:加上verify=false(默认是true)
import requests
#from requests.packages import urllib3
#urllib3.disable_warnings()
response = requests.get("https://www.12306.cn", verify=False)
print(response.status_code)
5.代理设置
proxies
6.超时时间
timeout,单位:毫秒
7.重定向
allow_rediects
还有几个访问参数介绍:
auth:认证,接受元祖
import requests
response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)
stream:是否下载获取的内容
cert:保存本地SSL证书路径
8.异常处理
所有的异常都是在requests.excepitons中:
示例:
import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:
response = requests.get("http://httpbin.org/get",timout=0.1)
print(response.status_code)
except ReadTimeout:
print("timeout")
except ConnectionError:
print("connection Error")
except RequestException:
print("error")
测试可以发现,首先被捕捉的异常是timeout超时异常,当把网络断掉就会捕捉到ConnectionError连接异常,如果前面异常都没有捕捉到,最后也可以通过RequestExctption捕捉到。
以上是requests的基本用法介绍,在实战中会遇到更复杂的使用~