Python+requests 之GET请求

1.配置环境

安装requests包:python  -m pip install requests


2.发送GET请求

import requests
r = requests.get("http://httpbin.org/get")

3. 添加headler和cookies

import requests
header = {
	"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"
}

cookie = {
	"PSTM": "553180542",
	"HMACCOUNT": "BA4C08D999D27E4E"
}

r = requests.get(url="http://httpbin.org/get", headers=header, cookies=cookie)
print(r.text)                            # 查看打印结果headers中的Cookie和User-Agent的values

4.带参请求

import requests
payload = {
	'name': 'sitven',
	'age': 25,
    'time':"2019-03-08"
}
req = requests.get(url="http://httpbin.org/get", params=payload)
print(req.text)                        # 查看返回信息args的value

5.获取响应信息

import requests
r = requests.get("http://httpbin.org/get")
print(r.text)			 # 字符串方式的响应体,会自动根据响应头部的字符编码进行解码
print(r.status_code)     # 响应状态码
print(r.json())          # Requests中内置的JSON解码器
print(r.headers)         # 以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None

r = requests.get("https://www.baidu.com")
print(r.content)         # 字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
print(r.url)             # 获取url
print(r.encoding)        # 编码格式
print(r.cookies)         # 获取cookie
print(r.raw)             # 获取原始响应体
print(r.history)         # 请求历史

 

你可能感兴趣的:(Requests接口自动化)