https://docs.python-requests.org/en/master/user/quickstart/

Requests库的七个主要方法

方法  说明
requests.request() 构造一个请求,支撑以下各方法的基础方法
requests.get() 获取HTML网页的主要方法,对应于HTTP的GET
requests.head() 获取HTML网页的头信息的方法,对应于HTTP的HEAD
requests.post() 向HTML网页提交POST请求的方法,对应于HTTP的POST
requests.put()  向HTML网页提交PUT请求的方法,对应于HTTP的PUT
requests.patch()  向HTML网页提交局部修改请求,对应于HTTP的PATCH
requests.delete()  向HTML网页提交删除请求的方法,对应于HTTP的DELETE

requests库的异常

属性   说明
r.status_code HTTP请求的返回状态,200表求连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content HTTP响应内容的二进制形式
r.url 返回URL实际参数
r.json
r.raw 数据流方式下载
r.iter_content 边下载边存储
r.headers
r.cookies
r.history 重定向

 r = requests.get(url, params = None, **kwargs)

构造一个向服务器请求资源的Request对象(Request),并且get方法返回一个包含服务器资源的Response对象;

requests.get函数的完整参数如下:

  requests.get(url, params = None, **kwargs)

        url: 拟获取页面的url链接

        params: url中额外参数,字典或字节流格式,可选

        **kwargs: 12个控  访问的参数

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> rl = requests.get('https://httpbin.org/get', params=payload)

Requests库的2个重要的对象 Request 和 Response对象(Response对象包含爬虫返回的所有内容)

属性   说明
r.status_code HTTP请求的返回状态,200表求连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content

HTTP响应内容的二进制形式

>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> r.text   #发现是乱码

>>> r.encoding   #查看它的编码

'ISO-8859-1'
>>> r.apparent_encoding  #再查看它的apparent_encoding编码

'utf-8'

>>> r.encoding ='utf-8'   #用'utf-8'编码来替换'ISO-8859-1'这个编码。
>>> r.text                        #结果可以正常显示网页内容

r.url

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}>>> r = requests.get('https://httpbin.org/get', params=payload)
>>> print(r.url)
https://httpbin.org/get?key1=value1&key2=value2&key2=value3

Response Content

r.text

>>> import requests>>> r = requests.get('https://api.github.com/events')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...

r.encoding

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

r.encoding:如果header中不存在charset,则认为编码为'ISO-8859-1'

r.apparent_encoding: 根据网页内容分析出的编码方式

Binary Response Content

r.content

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

gzip and deflate自动解码

>>> from PIL import Image
>>> from io import BytesIO>>> i = Image.open(BytesIO(r.content))

JSON Response Content

r.json

>>> import requests>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{'repository': {'open_issues': 0, 'url': 'https://github.com/...

异常

simplejson.JSONDecodeError /json.JSONDecodeError       内容包含无效json或者204 (No Content)

Raw Response Content

r.raw

>>> r = requests.get('https://api.github.com/events', stream=True)>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'with open(filename, 'wb') as fd:for chunk in r.iter_content(chunk_size=128):fd.write(chunk)

stream=True        初始request中必须设置该参数可获得raw数据

r = requests.get('http://httpbin.org/stream/20', stream=True)

https://www.jianshu.com/p/9ccebab67cc1

r.iter_content
r._iter_lines

url = "http://wx4.sinaimg.cn/large/d030806aly1fq1vn8j0ajj21ho28bduy.jpg"rsp = requests.get(url, stream=True)
with open('1.jpg', 'wb') as f:for i in rsp.iter_content(chunk_size=1024): # 边下载边存硬盘, chunk_size 可以自由调整为可以更好地适合您的用例的数字f.write(i)

当流下载时,用Response.iter_content更方便些。requests.get(url)默认是下载在内存中的,下载完成才存到硬盘上,可以用Response.iter_content 来边下载边存硬盘

Response.iter_content将自动解码gzipdeflate 传输编码。 Response.raw是一个原始字节流——它不会转换响应内容。如果您确实需要访问返回的字节,请使用Response.raw.

响应状态码和异常

r.status_code

>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200# Requests 还带有一个内置的状态代码查找对象,以便于参考:>>> r.status_code == requests.codes.ok
True

r.raise_for_status()

>>> bad_r = requests.get('https://httpbin.org/status/404')
>>> bad_r.status_code
404>>> bad_r.raise_for_status()
Traceback (most recent call last):File "requests/models.py", line 832, in raise_for_statusraise http_error
requests.exceptions.HTTPError: 404 Client Error

如果我们发出了错误的请求(4XX 客户端错误或 5XX 服务器错误响应),我们可以使用以下命令引发它 Response.raise_for_status()

但是,因为我们status_coder200,当我们调用 raise_for_status()我们得到:

>>> r.raise_for_status()
None

ConnectionError         网络问题(例如 DNS 故障、拒绝连接等)

HTTPError                 HTTP 请求返回不成功的状态代码

requests.exceptions.Timeout

TooManyRedirects        请求超过配置的最大重定向数

Requests 显式引发的所有异常都继承自 requests.exceptions.RequestException

响应头

r.headers

>>> r.headers
{'content-encoding': 'gzip','transfer-encoding': 'chunked','connection': 'close','server': 'nginx/1.0.4','x-runtime': '148ms','etag': '"e1ca502697e5c9317743dc078f67693f"','content-type': 'application/json'
}

字典很特别:它只是为 HTTP 标头而制作的。根据 RFC 7230

>>> r.headers['Content-Type']
'application/json'>>> r.headers.get('content-type')
'application/json'

cookies

快速访问cookies

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)>>> r.cookies['example_cookie_name']
'example_cookie_value'

发送cookies

>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Cookies 在 a 中返回RequestsCookieJar,它的作用类似于 adict但也提供了更完整的接口,适合在多个域或路径上使用。Cookie jar 也可以传递给请求

>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'https://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'

重定向和历史记录

r.history

例如,GitHub 将所有 HTTP 请求重定向到 HTTPS:

>>> r = requests.get('http://github.com/')>>> r.url
'https://github.com/'>>> r.status_code
200>>> r.history
[<Response [301]>]

allow_redirects参数禁用重定向处理:

>>> r = requests.get('http://github.com/', allow_redirects=False)>>> r.status_code
301>>> r.history
[]

超时 timeout

告诉请求在给定的秒数后停止等待响应timeout

>>> requests.get('https://github.com/', timeout=0.001)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

timeout对整个响应下载没有时间限制;相反,如果服务器在timeout几秒钟内没有发出响应(更准确地说,如果在几秒钟内没有在底层套接字上接收到字节),则会引发异常timeout。如果未明确指定超时,则请求不会超时。

python request.get相关推荐

  1. Python+request+ smtplib 测试结果html报告邮件发送(上)《五》

    此方法通用适合所有邮箱的使用,只需注意几个点,如下: QQ邮箱.其他非QQ邮箱的写法,区别点如下: #--------------------------使用腾讯企业邮箱作为发件人的操作如下----- ...

  2. python request 报错 #No JSON object could be decoded

    python request 报错 #No JSON object could be decoded Python 使用request 发起post请求报错如下 报错如下 解决方案如下 Python ...

  3. YDOOK: Sanic: Python request post请求 上传照片或文件 详细具体步骤 亲测可用!

    YDOOK: Sanic: Python request post请求 上传照片或文件 详细具体步骤 亲测可用! ©YDOOK JYLin 1. 项目目录架构: Upload result: 上传结果 ...

  4. Python Request POST 上传文件 Multipart/form-data

    项目场景: 我的第一个博客:使用python request模块向服务器接口上传图片 问题描述 某app上传图片接口的包 原因分析: 问题的关键词:请求头 Content-Type:multipart ...

  5. Python request简单使用

    欢迎加入学习交流QQ群:657341423 python request模块通过模拟用户访问web网站,实际运用到Html的post,get的方法实现网站互动.这个需要了解Html的post,get的 ...

  6. python request microsoft graph_Python request.headers方法代码示例

    本文整理汇总了Python中flask.request.headers方法的典型用法代码示例.如果您正苦于以下问题:Python request.headers方法的具体用法?Python reque ...

  7. 斗鱼美女主播封面爬取 python request urlretrieve jsonpath 爬虫

    斗鱼美女主播封面爬取 python request urlretrieve jsonpath 爬虫 输出结果 

  8. Python+Request【第二章】处理数据源信息

    Python+Request[第二章]处理数据源信息 config文件 配置config 示例代码 代码图示 读取config 示例代码 代码图示 封装config_utils 示例代码 excel文 ...

  9. python request.get()_使用Python request.get解析无法一次加载的html代码

    我正在尝试编写一个Python脚本,该脚本将定期检查网站以查看某项是否可用.过去,我已经成功使用了request.get,lxml.html和xpath来自动执行网站搜索.对于此特定URL(http: ...

  10. python request url 转义_Python多线程抓取Google搜索链接网页

    1)urllib2+BeautifulSoup抓取Goolge搜索链接 近期,参与的项目需要对Google搜索结果进行处理,之前学习了Python处理网页相关的工具.实际应用中,使用了urllib2和 ...

最新文章

  1. 12种主要的Dropout方法:用于DNNs,CNNs,RNNs中的数学和可视化解释
  2. python 今日头条 控制手机_千米矿井开5G无人运矿车像打游戏今日头条手机光明网...
  3. 计算机硬盘清理,电脑磁盘清理,详细教您电脑磁盘怎么清理
  4. 信息系统项目管理师优秀论文:项目沟通管理202111
  5. apache php mysql下载_linux+apache+php+mysql 安装
  6. 关于使用Nginx服务器发布静态网页或者代理
  7. simulink仿真及代码生成技术入门到精通_Simulink仿真零基础入门到精通实用教学教程 自学全套...
  8. 01算法 java_蓝桥杯:基础练习 01字串【JAVA算法实现】
  9. Magento中直接使用SQL语句
  10. oracle 分表和分区哪个好_互联网大厂有哪些分库分表的思路和技巧?
  11. 借助计算机软件进行文学写作,网络文学创作对编辑提出的新要求及建议
  12. C#如何获得屏幕宽度和高度
  13. 计算机网络-路由器广域网配置
  14. 单片机C51继电器控制C语言,单片机控制继电器,51单片机控制继电器详细说明
  15. 教你恢复电脑被删的照片或视频,方法实用可收藏
  16. lidar及tof应用,三维点,线,面求解算法,手眼标定,点云匹配及三角剖分、结构光和TOF深度图
  17. Web项目中前端页面引用外部Js和Css的路径问题
  18. FastDFS集群tracker实现负载均衡
  19. Python学习(中一)
  20. [html] 写一个鼠标跟随的特效

热门文章

  1. 腾讯短网址/短链接url.cn生成接口工具推荐
  2. 比亚迪DiLink深体验:让科幻般的车生活都成为实现,智能网联集大成者张这样?...
  3. Git- Fast Forward和no fast forward
  4. 利用jmail qq邮箱发邮件 报错 解决方法
  5. 正则表达式的字符匹配(一)
  6. 苹果微信多开_怎样才能下载两个微信
  7. Soft-NMS – Improving Object Detection With One Line of Code
  8. perl中正则匹配中文字符
  9. SQL查询------模糊查询
  10. 【java】Deepin 解决JDK出现Picked up _JAVA_OPTIONS: -awt.useSystemAAFontSettings=gasp的问题