python模块之requests

python-requests

为啥不用urllib用requests,因为requests比urllib方便,requests是python实现的最简单的HTTP库。

各种请求方式

GET请求

import requests

response = requests.get('http://httpbin.org/get')
print(response.text)

output

{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
  },
  "origin": "183.221.76.133",
  "url": "http://httpbin.org/get"
}

如果想要在url查询字符串传递数据,在requests模块中可以用params关键字传递参数,然后用一个字典来传递这些参数。

import requests

data={
    "name":"Gsuhy",
    "age":19
    }

response=requests.get("http://httpbin.org/get",params=data)
print(response.text)
print(response.url)

output

{
  "args": {
    "age": "19",
    "name": "Gsuhy"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
  },
  "origin": "183.221.76.133",
  "url": "http://httpbin.org/get?name=Gsuhy&age=19"
}

http://httpbin.org/get?name=Gsuhy&age=19

添加header

我们如果直接用python中requests请求知乎的时候

import requests
response =requests.get("https://www.zhihu.com")
print(response.text)

会发现出现400 Bad Request

那么我们在chrome中输入chrome://version/查看 一下版本信息,找到用户代理,把这个添加到请求中就可以请求了。

import requests

headers={
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
    }
response =requests.get("https://www.zhihu.com",headers=headers)
print(response.text)

POST请求

就是requests.post()嘛,不说了不说了。。。

requests高级用法

文件上传

方法还是简单,构造一个字典,然后通过files参数传递。

import requests
files= {"files":open("git.jpeg","rb")}
response = requests.post("http://httpbin.org/post",files=files)
print(response.text)

获取cookie

import requests

response = requests.get("http://www.baidu.com")
print(response.cookies)

for key,value in response.cookies.items():
    print(key+"="+value)

   转载规则


《python模块之requests》 Gsuhy 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录