美文网首页
21 | Requests

21 | Requests

作者: 运维开发_西瓜甜 | 来源:发表于2020-01-01 23:23 被阅读0次

原文链接: https://www.jianshu.com/p/f4915b39257a
作者:shark

基本介绍

requests 模块可以模仿浏览器的行为。通常用于爬虫。

安装使用 pip3 install requests

一、get 方法

JSON 介绍

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。

我们通常使用到的 JSON 数据的表现形式如下:

'{"name": "shark", "age": 18}'
'[1, 2, 3, "lenovo"]'

'[{"name": "shark"}, {"name": "xiguatian"}]'

可以看出 JSON 数据中的字符串必须使用双引号,最外层使用单引号
JSON 包含有

  • 对象 ,就是一对儿大括号
  • 数组, 就是一对儿中括号
  • 字符串,必须使用双引号引起来
  • 数字

1. 基本使用

import requests
r = requests.get('https://api.github.com/events')

r 是返回的 Response对象。我们可以从这个对象中获取所有我们想要的信息。

r.status_code   # 响应状态码

r.content  # 二进制的响应体

r.text    # 普通文本形式的相应体

# 假如相应体是一个 JSON 的数据类型,可以使用如下方法直接转换为 Python 的数据类型
r.json

2. get方法的传参

In [25]: payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

In [26]: r = requests.get("http://httpbin.org/get", params=payload)

In [27]: r.url
Out[27]: 'http://httpbin.org/get?key1=value1&key2=value2&key2=value3'

二、post 方法

要实现这个,只需简单地传递一个字典给 data 参数。

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

传递 JSON 数据

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

还可以使用 json 参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能:

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, json=payload)

三、Custom Headers (自定义请求头)

如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了。

>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

四、Cookie

如果某个响应中包含一些 cookie,你可以快速访问它们:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

要想发送你的cookies到服务器,可以使用 cookies 参数:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

参考资料: https://2.python-requests.org//zh_CN/latest/user/quickstart.html

相关文章

网友评论

      本文标题:21 | Requests

      本文链接:https://www.haomeiwen.com/subject/xhjpoctx.html