1、Requests 安装 使用pip安装命令,打开doc窗口,输入【pip install requests】可以查看是否安装成功
pip install requests
2、get 基础请求
import requests
baidu_url = requests.get("https://www.baidu.com")
print(baidu_url.status_code)
3、get 参数请求
import requests
douban_url = "https://movie.douban.com/j/search_subjects"
douban_query = {
"type": "movie",
"tag": "华语",
"page_limit": 20,
"page_start": 0
}
douban_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
}
douban_request = requests.get(douban_url, params=douban_query, headers=douban_header)
# 打印请求的返回状态
print(douban_request.status_code)
# 打印请求的header
print(douban_request.request.headers)
# 打印结果
print(douban_request.json())
4、下载图片
import requests
douban_url = "https://movie.douban.com/j/search_subjects"
douban_query = {
"type": "movie",
"tag": "华语",
"page_limit": 20,
"page_start": 0
}
douban_header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
}
douban_request = requests.get(douban_url, params=douban_query, headers=douban_header)
# 打印请求的返回状态
print(douban_request.status_code)
# 打印请求的header
print(douban_request.request.headers)
# 打印结果
print(douban_request.json())
# 请求返回的结果
douban_res_data = douban_request.json()
# 从结果中获取指定信息
subjects = douban_res_data.get('subjects')
for subjects in subjects:
print(subjects.get('title'),subjects.get('cover'))
file_name = subjects.get('title')
file_url = subjects.get('cover')
r = requests.get(file_url, headers=douban_header)
with open(file_name+'.jpg', mode='wb') as file:
file.write(r.content)
5、post 请求【'Content-Type': 'application/json'】
import requests
url = "http://10.20.100.200:8095/api/user"
req_body = {
"user_name": "string",
"user_code": "string"
}
req = requests.post(url, json=req_body) # 'Content-Type': 'application/json'
print(req.status_code)
print(req.request.headers)
6、post 请求【'Content-Type': 'application/x-www-form-urlencoded'】
import requests
url = "http://10.20.100.200:8095/api/user"
req_body = {
"user_name": "string",
"user_code": "string"
}
req = requests.post(url, data=req_body) # 'Content-Type': 'application/x-www-form-urlencoded'
print(req.status_code)
print(req.request.headers)
* * *
|