Python 官方文档:入门教程 => 点击学习
在前面一节我们了解了 Urllib 的基本用法,但是其中确实有不方便的地方。比如处理网页验证、处理 Cookies 等等,需要写 Opener、Handler 来进行处理。为了更加方便地实现这些操作,在这里就有了更为强大的库 Request
在前面一节我们了解了 Urllib 的基本用法,但是其中确实有不方便的地方。比如处理网页验证、处理 Cookies 等等,需要写 Opener、Handler 来进行处理。为了更加方便地实现这些操作,在这里就有了更为强大的库 Requests,有了它,Cookies、登录验证、代理设置等等的操作都不是事儿。
那么接下来就让我们来领略一下它的强大之处吧。
本节我们首先来了解下 Requests 库的基本使用方法。
在本节开始之前请确保已经正确安装好了 Requests 库,如果没有安装可以参考第一章的安装说明。
在 Urllib 库中有 urlopen() 的方法,实际上它是以 GET 方式请求了一个网页。
那么在 Requests 中,相应的方法就是 get() 方法,是不是感觉表达更明确一些?
下面我们用一个实例来感受一下:
import requests
r=requests.get('Http://httpbin.org/get')
print(type(r),r.status_code,type(r.text),r.text,type(r.cookies),r.cookies,sep='\n')
运行结果如下:
<class 'requests.models.Response'>
200
<class 'str'>
{
"args": {},
"headers": {
"Accept": "**",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"origin": "122.4.215.33",
"url": "http://httpbin.org/get"
}
可以发现我们成功发起了 GET 请求,返回的结果中包含了 Request Headers、URL、IP 等信息。
那么 GET 请求,如果要附加额外的信息一般是怎样来添加?比如现在我想添加两个参数,名字 name 是 germey,年龄 age 是 22。构造这个请求链接是不是我们要直接写成:
r = requests.get('http://httpbin.org/get?name=g...;age=22')
可以是可以,但是不觉得很不人性化吗?一般的这种信息数据我们会用字典来存储,那么怎样来构造这个链接呢?
同样很简单,利用 params 这个参数就好了。
实例如下:
import requests
data = {
'name': 'germey',
'age': 22
}
r = requests.get("http://httpbin.org/get", params=data)
print(r.text)
运行结果如下:
{
"args": {
"age": "22",
"name": "germey"
},
"headers": {
"Accept": "**",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "18",
"Content-Type": "application/x-www-fORM-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-requests/2.10.0"
},
"JSON": null,
"origin": "182.33.248.131",
"url": "http://httpbin.org/post"
}
可以发现,成功获得了返回结果,返回结果中的 form 部分就是提交的数据,那么这就证明 POST 请求成功发送了。
发送 Request 之后,得到的自然就是 Response,在上面的实例中我们使用了 text 和 content 获取了 Response 内容,不过还有很多属性和方法可以获取其他的信息,比如状态码 Status Code、Headers、Cookies 等信息。
下面用一个实例来感受一下:
import requests
r = requests.get('http://www.baidu.com')
print(type(r.status_code), r.status_code)
print(type(r.headers), r.headers)
print(type(r.cookies), r.cookies)
print(type(r.url), r.url)
print(type(r.history), r.history)
在这里分别打印输出了 status_code 属性得到状态码, headers 属性得到 Response Headers,cookies 属性得到 Cookies,url 属性得到 URL,history 属性得到请求历史。
运行结果如下:
<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 17 Jun 2019 11:01:04 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:32 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
<class 'requests.cookies.RequestsCookiejar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
<class 'str'> http://www.baidu.com/
<class 'list'> []
可以看到,headers 还有 cookies 这两个属性得到的结果分别是 CaseInsensitiveDict 和 RequestsCookieJar 类型。
在这里 Status Code 常用来判断请求是否成功,Requests 还提供了一个内置的 Status Code 查询对象 requests.codes。
用一个实例来感受一下:
import requests
r = requests.get('http://www.jianshu.com')
exit() if not r.status_code == requests.codes.ok else print('Request Successfully')
在这里,通过比较返回码和内置的成功的返回码是一致的,来保证请求得到了正常响应,输出成功请求的消息,否则程序终止,在这里我们用 requests.codes.ok 得到的是成功的状态码 200。
那么肯定不能只有 ok 这个条件码,下面列出了返回码和相应的查询条件:
# Informational.
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')
Python资源分享qun 784758214 ,内有安装包,pdf,学习视频,这里是Python学习者的聚集地,零基础,进阶,都欢迎
比如如果我们想判断结果是不是 404 状态,可以用 requests.codes.not_found 来比对。
本节我们了解了利用 Requests 模拟最基本的 GET 和 POST 请求的过程,关于更多高级的用法,会在下一节进行讲解。
--结束END--
本文标题: Python3网络爬虫实战-24、req
本文链接: https://www.lsjlt.com/news/192461.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0