当前位置:   article > 正文

Python发送网络请求(requests)_python 网络请求

python 网络请求

Python发送网络请求(requests)

Python已经是广泛使用的脚本语言了,我们可以使用requests库进行网络请求。

PyPI中搜索requests,就可以找到这个库

1. 安装
pip install requests
  • 1

安装完成后,在py脚本中使用库,需要import进行代码导入

import requests
  • 1
2. 发送请求
2.1 发送GET请求
import requests

r = requests.get('https://api.github.com/events')
print(r)
  • 1
  • 2
  • 3
  • 4

如果请求成功,返回的结果为 Response 对象

GET 请求也是可以传递参数的,上面的代码演示的是无参数形式,可以通过 params 参数传递 GET 参数。

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)
  • 1
  • 2
  • 3
  • 4
2.2 发送POST请求
import requests

r = requests.post('https://httpbin.org/post', data={'key': 'value'})
print(r)
  • 1
  • 2
  • 3
  • 4

POST请求通过data参数传递请求参数

2.3 输出其他信息
import requests

r = requests.get('https://api.github.com/events')
print(r)
print(r.encoding);
print(r.url);
print(r.status_code);
print(r.cookies);
print(r.headers);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

encoding 表示编码;url 表示完整请求路径;status_code 表示 http 请求状态码;cookies 表示 cookies 信息;headers 表示请求头信息。

3. 小结

Python的requests 库可以实现网络请求,可以以非常简单的API发送GET、POST请求,并可以根据得到的Response对象获取请求结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/463244
推荐阅读
相关标签
  

闽ICP备14008679号