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

一、引子

import requestsresp = requests.get("https://www.baidu.com/")
print(type(resp))  # <class 'requests.models.Response'>
print(resp.status_code)  # 200
# 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", "123"))
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")

转载于:https://www.cnblogs.com/believepd/p/10657681.html

爬虫之Requests库相关推荐

  1. 煎蛋网妹子图爬虫(requests库实现)

    煎蛋网妹子图爬虫(requests库实现) 文章目录 煎蛋网妹子图爬虫(requests库实现) 一.前言 环境配置 二.完整代码 一.前言 说到煎蛋网爬虫,相比很多人都写过,我这里试着用reques ...

  2. python爬虫基础-requests库

    python爬虫基础-requests库 python爬虫 1.什么是爬虫? 通过编写程序,模拟浏览器上网,然后让其去互联网上抓取数据的过程. 注意:浏览器抓取的数据对应的页面是一个完整的页面. 为什 ...

  3. python的requests库的添加代理_python爬虫之requests库使用代理

    python爬虫之requests库使用代理 发布时间:2020-03-25 17:00:54 来源:亿速云 阅读:110 作者:小新 今天小编分享的是关于python爬虫的requests库使用代理 ...

  4. 起点中文网爬虫实战requests库以及xpath的应用

    起点中文网爬虫实战requests库以及xpath的应用 知识梳理: 本次爬虫是一次简单的复习应用,需要用到requests库以及xpath. 在开始爬虫之前,首先需要导入这两个库 import re ...

  5. Python网络爬虫之requests库Scrapy爬虫比较

    requests库Scrapy爬虫比较 相同点: 都可以进行页面请求和爬取,Python爬虫的两个重要技术路线 两者可用性都好,文档丰富,入门简单. 两者都没有处理JS,提交表单,应对验证码等功能(可 ...

  6. python爬取图片的库_16-python爬虫之Requests库爬取海量图片

    Requests 是一个 Python 的 HTTP 客户端库. Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和P ...

  7. python怎么安装requests库-Python爬虫入门requests库的安装与使用

    Requests库的详细安装过程 对于初学Python爬虫小白,认识和使用requests库是第一步,requests库包含了网页爬取 的常用方法.下面开始安装requests库. 1.检查是否安装过 ...

  8. python爬虫百科-Python爬虫之requests库介绍(一)

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

  9. python爬虫requests实战_Python爬虫之requests库网络爬取简单实战

    实例1:直接爬取网页 实例2 : 构造headers,突破访问限制,模拟浏览器爬取网页 实例3 : 分析请求参数,构造请求参数爬取所需网页 实例4: 爬取图片 实例5: 分析请求参数,构造请求参数爬取 ...

  10. python爬虫requests库_python爬虫使用Requests库 - pytorch中文网

    在入门教程中我们介绍了urllib库和urllib2的用法,同时我们了解一些爬虫的基础以及对爬虫有了基本的了解.其实在我们生产环境中,使用Request库更加方便与实用,同时我们这需要短短的几行代码就 ...

最新文章

  1. 全球及中国天然香豆素行业竞争态势与投资份额调研报告2022版
  2. SQLite学习手册(实例代码一)
  3. excel xml mysql_数据库表转换为xml格式,excel转换为xml格式文件
  4. js利用localStorage和sessionStorage完成记住我功能
  5. C# Directory.Exists() 文件存在但返回一直为false
  6. OpenCV的数据类型——辅助对象
  7. 终于有人把大数据讲明白了。。。
  8. mysql sqlstate 08001_关于Toad连接DB2的sqlstate=08001错误
  9. OpenVINO 2019 R2.0 Custom Layer Implementation for linux(2)
  10. 【例题+习题】【数值计算方法复习】【湘潭大学】(三)
  11. file does not exist 阿里云OSS图片上传遇到的问题
  12. 计算机一级考试系统改革,以等级考试为导向的大学计算机改革
  13. 谈一下今天的网络赛。。。这次是真的弱爆了。。。。
  14. win7下對顯示器的電源的操作
  15. 蓝桥杯题目 abcde/fghij=n
  16. 直播视频分辨率码率参考设置
  17. [Egret学习笔记 二]MovieClip的使用
  18. 会议审批 查询会议签字
  19. 如何安装用友NC6.5
  20. 数据可能只有在你眼里才一文不值

热门文章

  1. linux备份能压缩吗,Linux备份与压缩命令
  2. oracle增量和全量的区别,ORACLE全备份和0级增量备份的区别
  3. 长沙android工程师,长沙安卓工程师辅导
  4. ubuntu 16.04安装网易云音乐
  5. 21天jmeter打卡day4-请求并查看响应信息
  6. spss分析qpcr数据_谁说菜鸟不会数据分析--SPSS篇
  7. Python测试转岗网络安全测试,挑战年薪30W+
  8. 测试专员如何编写优秀的测试代码·单元测试篇
  9. chrome vue.js插件文档_前端开发者必备的40个VSCode插件!
  10. 电商常用字体_字体商用有风险,侵权罚款上千万!告诉你怎么正确使用