首页 > 编程语言 > 详细

python--requests模块详解

时间:2020-09-27 17:04:24      阅读:31      评论:0      收藏:0      [点我收藏+]

GET请求

首先构造一个最简单的get请求,请求的链接为http://httpbin.org/get

 import requests                                            
  2 r = requests.get("http://httpbin.org/get")
  3 print(r.text)
#运行结果
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4", 
    "X-Amzn-Trace-Id": "Root=1-5f704dcf-78e431abe1d838c6c44e50ac"
  }, 
  "origin": "58.17.121.223", 
  "url": "http://httpbin.org/get"
}

可以发现我们成功的发起了get请求,并且返回结果中包括了请求头,URL,IP等信息

如果发起请求的URL地址需要参数,利用params这个参数

 import requests                                            
  2 date = {
  3         "name":"germey",
  4         "age":22
  5         }
  6 r = requests.get("http://httpbin.org/get",params = date)
  7 
  8 print(r.text)
#运行结果
{
  "args": {
    "age": "22", 
    "name": "germey"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4", 
    "X-Amzn-Trace-Id": "Root=1-5f704f27-854822ce60e1c5f94da41517"
  }, 
  "origin": "58.17.121.223", 
  "url": "http://httpbin.org/get?name=germey&age=22"
}

通过运行结果我们可以判断,请求的链接自动被构造成了:http://httpbin.org/get?age = 22&name= germey

添加headers

有些网站如果不传递headers则会被禁止访问,所以一般在发起请求之前我们都要进行UA伪装

POST请求

 import requests                                            
  2 data = {"name":"germey","age":22}
  3 r = requests.post("http://httpbin.org/post",data = data)
  4 print(r.text)
#运行结果
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "22", 
    "name": "germey"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "18", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4", 
    "X-Amzn-Trace-Id": "Root=1-5f70517c-43382ec6284d9ce2a3cd28f1"
  }, 
  "json": null, 
  "origin": "58.17.121.223", 
  "url": "http://httpbin.org/post"
}

其中form就是需要提交的数据

 

python--requests模块详解

原文:https://www.cnblogs.com/zoutingrong/p/13740477.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!