官方文档:http://cn.python-requests.org/zh_CN/latest/

一、引子

import requests

resp = requests.get("https://www.baidu.com/")
print(type(resp)) # <class 'requests.models.Response'>
print(resp.status_code) #
# print(resp.text)
print(type(resp.text)) # <class 'str'>
# print(resp.text)
print(resp.cookies)

各种请求方式:

import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

二、请求

GET请求

基本写法:

import requests
resp = requests.get("http://httpbin.org/get")
print(resp.text)

带参数get请求:

# 方式1
resp = requests.get("http://httpbin.org/get?name=pd&age=18")
print(resp.text)
# 方式2
params = {
"name": "pd",
"age": 18
}
resp = requests.get("http://httpbin.org/get", params=params)
print(resp.text)

解析json:

resp = requests.get("http://httpbin.org/get")
print(resp.json()) # 相当于json.loads(resp.text)
print(type(resp.text)) # <class 'str'>
print(type(resp.json())) # <class 'dict'>

获取二进制数据:

resp = requests.get("https://github.com/favicon.ico")
print(type(resp.text)) # <class 'str'>
print(type(resp.content)) # <class 'bytes'>
print(resp.text)
print(resp.content) # 获取非文本响应内容 with open("favicon.ico", "wb") as f:
f.write(resp.content)

添加请求头:

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
resp = requests.get("https://www.zhihu.com/explore", headers=headers)
print(resp.text)

POST请求

基本操作:

data = {"name": "pd", "age": 18}
resp = requests.post("http://httpbin.org/post", data=data)
print(resp.text)

添加请求头:

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
data = {"name": "pd", "age": 18}
resp = requests.post("http://httpbin.org/post", data=data, headers=headers)
print(resp.text)

三、响应

响应属性:

resp = requests.get("https://www.jianshu.com")
print(type(resp.status_code), resp.status_code) # <class 'int'> 200
print(type(resp.headers), resp.headers)
print(type(resp.cookies), resp.cookies) # <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie locale=zh-CN for www.jianshu.com/>]>
print(type(resp.url), resp.url) # <class 'str'> https://www.jianshu.com/
print(type(resp.history), resp.history) # <class 'list'> []

状态码判断:

resp = requests.get("https://www.jianshu.com")
exit() if not resp.status_code == requests.codes.forbidden else print("403 Forbidden")
response = requests.get("http://www.baidu.com")
exit() if not response.status_code == 200 else print("Request Successfully")
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',), # 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'),

状态码信息

四、高级操作

文件上传

files = {"file": open("favicon.ico", "rb")}
resp = requests.post("http://httpbin.org/post", files=files)
print(resp.text)

获取cookie

resp = requests.get("https://www.baidu.com")
print(resp.cookies) # <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
for key, value in resp.cookies.items():
print(key + "=" + value) # BDORZ=27315

会话维持

用来做模拟登录。

requests.get("http://httpbin.org/cookies/set/num/123456")  # 设置cookie
resp = requests.get("http://httpbin.org/cookies")
print(resp.text) # {"cookies": {}} cookies为空是因为发起两次请求,而两此请求是完全独立的过程

声明一个session对象发起两次请求:

s = requests.Session()
s.get("http://httpbin.org/cookies/set/num/123456")
resp = s.get("http://httpbin.org/cookies")
print(resp.text) # {"cookies": {"num": "123456"}}

证书验证

如果要爬取上述这种网站的话:

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
resp = requests.get("https://www.xxx.com", verify=False)
print(resp.status_code)

代理设置

proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}
resp = requests.get("https://www.xxx.com", proxies=proxies)
print(resp.status_code)

如果不是http、https代理,而是socks代理:

pip3 install 'requests[socks]'
proxies = {
"http": "socks5://127.0.0.1:9742",
"https": "socks5://127.0.0.1:9742"
}
response = requests.get("https://www.xxx.com", proxies=proxies)
print(response.status_code)

超时设置

为防止服务器不能及时响应,大部分发至外部服务器的请求都应该带着 timeout 参数。在默认情况下,除非显式指定了 timeout 值,requests 是不会自动进行超时处理的。如果没有 timeout,你的代码可能会挂起若干分钟甚至更长时间。

import requests
from requests import exceptions
try:
resp = requests.get("http://httpbin.org/get", timeout=0.5)
print(resp.status_code)
except exceptions.ReadTimeout:
print("ReadTimeout")
except exceptions.ConnectTimeout:
print("ConnectTimeout")

认证设置

有些网站需要登录才能看到里面的内容:

import requests
from requests.auth import HTTPBasicAuth
resp = requests.get("http://111.11.11.11:9001", auth=HTTPBasicAuth("user", ""))
print(resp.status_code)

异常处理

http://www.python-requests.org/en/master/api/#exceptions

import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
resp = requests.get("http://httpbin.org/get", timeout=0.5)
print(resp.status_code)
except ReadTimeout:
print("Timeout")
except ConnectionError:
print("Connection error")
except RequestException:
print("Error")

爬虫之Requests库的更多相关文章

  1. Python爬虫之requests库介绍(一)

    一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...

  2. python爬虫之requests库

    在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...

  3. 爬虫相关--requests库

    requests的理想:HTTP for Humans 一.八个方法 相比较urllib模块,requests模块要简单很多,但是需要单独安装: 在windows系统下只需要在命令行输入命令 pip ...

  4. Python爬虫:requests 库详解,cookie操作与实战

    原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...

  5. Python爬虫之requests库的使用

    requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 "HTTP for ...

  6. 【Python爬虫】爬虫利器 requests 库小结

    requests库 Requests 是一个 Python 的 HTTP 客户端库. 支持许多 HTTP 特性,可以非常方便地进行网页请求.网页分析和处理网页资源,拥有许多强大的功能. 本文主要介绍 ...

  7. 爬虫值requests库

    requests简介 简介 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 ,使用起来比urllib简洁很多 因为是第三方库, ...

  8. (爬虫)requests库

    一.requests库简介 urllib库和request库的作用一样,都是服务器发起请求数据,但是requests库比urllib库用起来更方便,它的接口更简单,选用哪种库看自己. 如果没有安装过这 ...

  9. 【Python爬虫】Requests库的基本使用

    Requests库的基本使用 阅读目录 基本的GET请求 带参数的GET请求 解析Json 获取二进制数据 添加headers 基本的POST请求 response属性 文件上传 获取cookie 会 ...

  10. python网络爬虫之requests库

    Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_fun ...

随机推荐

  1. shell脚本自动更新git

    gitpull.sh #!/bin/bash cd /home/wwwroot/default/mouse && git pull cd /home/wwwroot/default/s ...

  2. flash builder 4.6 下载完成后安装不成功

    从网上下载了一下flash builder 4.6 下载完成后安装不成功,说是有一个安装被挂起,不成安装成功结果从注册表中删除了pendingobject,还是不行,没有办法,从网上搜了一下,发现了大 ...

  3. USACO 刷题有感

    最近每天都尽量保持着每天一道USACO的题目,呵呵,一开始都是满简单的,一看题目基本上思路就哗啦啦地出来了,只不过代码实现有点麻烦,花了一些时间去调试,总体感觉还不错,但是越往后做,应该就很难保持一天 ...

  4. BZOJ_4802_欧拉函数_MR+pollard rho+欧拉函数

    BZOJ_4802_欧拉函数_MR+pollard rho+欧拉函数 Description 已知N,求phi(N) Input 正整数N.N<=10^18 Output 输出phi(N) Sa ...

  5. ios下使用overflow scroll情况下,到达最极端的情况时会拖动整个页面的解决办法

    今天开发ipad webapp时,遇到个问题就是在支持内部滚动(overflow:scroll)的页面中,在滚到到最极端(最上或者最下时),会拖动整个页面,带来不好的用户体验. 方法一,从网上找到的: ...

  6. web界面bug-临时

    一.登录页面 二.首页 三.项目 四.项目池 五.专家管理 六.审批 七.日/周报 八.设置

  7. 洛谷 P1865 A % B Problem(求区间质数个数)

    题目背景 题目名称是吸引你点进来的 实际上该题还是很水的 题目描述 区间质数个数 输入输出格式 输入格式: 一行两个整数 询问次数n,范围m 接下来n行,每行两个整数 l,r 表示区间 输出格式: 对 ...

  8. Python中re操作正则表达式

    在python中使用正则表达式 1.转义符 正则表达式中的转义: '\('表示匹配小括号 [()+*/?&.] 在字符组中一些特殊的字符会现出原形 所有的\s\d\w\S\D\W\n\t都表示 ...

  9. C#常量知识整理

    整数常量 整数常量可以是十进制.八进制或十六进制的常量.前缀指定基数:0x 或 0X 表示十六进制,0 表示八进制,没有前缀则表示十进制. 整数常量也可以有后缀,可以是 U 和 L 的组合,其中,U ...

  10. BFS POJ 3126 Prime Path

    题目传送门 /* 题意:从一个数到另外一个数,每次改变一个数字,且每次是素数 BFS:先预处理1000到9999的素数,简单BFS一下.我没输出Impossible都AC,数据有点弱 */ /**** ...