python爬虫之requests的基础使用

1、先安装requests库,打开cmd,输入:pip install requests

2、弄明白几个请求函数的关系:

(1)、GET: 请求指定的页面信息,并返回实体主体。
(2)、HEAD: 只请求页面的首部。
(3)、POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
(4)、PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
(5)、DELETE: 请求服务器删除指定的页面。
(6)、get 和 post比较常见 GET请求将提交的数据放置在HTTP请求协议头中
(7)、POST提交的数据则放在实体数据中
3、GET请求

GET请求将提交的数据放置在HTTP请求协议头中

代码如下:

#导入requests模块
import requests
#请求指定的页面信息,并返回实体主体
response=requests.get('http://httpbin.org/get')
# 打印
print(response.text)

结果:

{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5e6f446c-68ae1f7e19aa9f549afc9fc8"
},
"origin": "182.111.11.140",
"url": "http://httpbin.org/get"
}


Process finished with exit code 0

例如,还有个代码:

# 导入requests模块
import requests
# 获取一个网页响应对象
response = requests.get("https://www.baidu.com")
# 打印响应的类型:requests.models.Response'
print(type(response))
#打印响应的状态代码:200
print(response.status_code)
# 打印响应的文本的类型:str
print(type(response.text))
# .text返回的是unicode类型
print(response.text)

4、带参数的GET请求

代码如下:

#导入requests模块
import requests
#请求指定的页面信息,并返回实体主体
response=requests.get('http://httpbin.org/get?name=choa&age=24')
# 打印
print(response.text)

结果:

{
"args": {
"age": "24",
"name": "choa"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5e6f44cd-8c9acce813e8a072566e51c6"
},
"origin": "182.111.11.140",
"url": "http://httpbin.org/get?name=choa&age=24"
}


Process finished with exit code 0

也可以用params的方法:

代码如下:

#导入requests模块
import requests
# 参数
data = {"name": "choa", "age" : 24}
#请求指定的页面信息,并返回实体主体
response=requests.get('http://httpbin.org/get',params=data)
# 打印
print(response.text)

结果同上。

5、以json形式返回

代码如下:

#导入requests模块
import requests
import json
# 参数
data = {"name": "choa", "age" : 24}
#请求指定的页面信息,并返回实体主体
response=requests.get('http://httpbin.org/get',params=data)
# 以json形式返回
print(response.json())
# 以json形式返回
print(json.loads(response.text))
# 以json返回类型格式:dict
print(type(response.json()))

结果:

{'args': {'age': '24', 'name': 'choa'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5e6f4878-049cabfd40bd7868b2ec3965'}, 'origin': '182.111.11.140', 'url': 'http://httpbin.org/get?name=choa&age=24'}
{'args': {'age': '24', 'name': 'choa'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5e6f4878-049cabfd40bd7868b2ec3965'}, 'origin': '182.111.11.140', 'url': 'http://httpbin.org/get?name=choa&age=24'}
<class 'dict'>

6、以二进制形式返回

代码如下:

#导入requests模块
import requests
import json
# 参数
data = {"name": "choa", "age" : 24}
#请求指定的页面信息,并返回实体主体
response=requests.get('http://httpbin.org/get',params=data)
#以字符串形式返回
print(response.text)
# 以二进制形式返回
print(response.content)
# 类型:bytes
print(type(response.content))
# 类型:str
print(type(response.text))

结果:

{
"args": {
"age": "24",
"name": "choa"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5e6f4a9f-f2e073003d68b200d9560600"
},
"origin": "182.111.11.140",
"url": "http://httpbin.org/get?name=choa&age=24"
}

b'{\n "args": {\n "age": "24", \n "name": "choa"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.23.0", \n "X-Amzn-Trace-Id": "Root=1-5e6f4a9f-f2e073003d68b200d9560600"\n }, \n "origin": "182.111.11.140", \n "url": "http://httpbin.org/get?name=choa&age=24"\n}\n'
<class 'bytes'>
<class 'str'>

7、添加headers

代码如下:

#导入requests模块
import requests
# 导入json解析模块
import json
#请求指定的页面信息,并返回实体主体
response=requests.get('https://www.zhihu.com/explore')
#以字符串形式返回
print(response.text)

结果:

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>

看来这样我们爬取不到信息,如果我们传入一个headers:

#导入requests模块
import requests
# 导入json解析模块
import json
#传入一个headers
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0'
}
#请求指定的页面信息,并返回实体主体
response=requests.get('https://www.zhihu.com/explore', headers=headers)
#以字符串形式返回
print(response.text)

 这里就可以获取知乎探索页面左右的源文件。

8、POST请求

POST:请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。

代码如下:

#导入requests模块
import requests
# 导入json模块
import json
# 定义一个dict
data={"name":"Mr_choa1","age":24}
# post请求
response=requests.post("http://httpbin.org/post",data=data)
# 以字符串形式返回
print(response.text)

结果:

{
"args": {},
"data": "",
"files": {},
"form": {
"age": "24",
"name": "Mr_choa1"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "20",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5e71bb4e-e7d00420413b0620204749e0"
},
"json": null,
"origin": "111.77.5.100",
"url": "http://httpbin.org/post"
}


Process finished with exit code 0

9、response到底是什么?答案:一个响应

# 导入requests模块
import requests
# get请求
response = requests.get('http://www.jianshu.com')
# 状态代码类型:int 状态代码是403
print(type(response.status_code), response.status_code)
# headers类型:requests.structures.CaseInsensitiveDict
print(type(response.headers), response.headers)
# cookies类型:requests.cookies.RequestsCookieJar
print(type(response.cookies), response.cookies)
# url类型:str
print(type(response.url), response.url)
# history类型:list
print(type(response.history), response.history)

结果:

<class 'int'> 403
<class 'requests.structures.CaseInsensitiveDict'> {'Server': 'Tengine', 'Date': 'Wed, 18 Mar 2020 06:18:35 GMT', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Content-Encoding': 'gzip'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
<class 'str'> https://www.jianshu.com/
<class 'list'> [<Response [301]>]

Process finished with exit code 0

我们验证响应http://www.jianshu.com的headers时:

 10、常见网络状态代码:

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'),

 

 

 

 

本文参考博客:https://blog.csdn.net/byweiker/article/details/79234853

 

posted @ 2020-03-16 15:37  Mr_choa  阅读(469)  评论(0编辑  收藏  举报