解释:向服务器发送请求
requests.get('www.baidu.com')
requests.post('www.baidu.com')
params = {
"id":16,
"name":"jack"
}
requests.get('www.baidu.com',params=params)
# 默认发送字符串
params = {
"id":16,
"name":"jack"
}
requests.post('www.baidu.com',data=params) #这里要写data
# 默认发送字符串
解释:发送json数据
params = {
"id":16,
"name":"jack"
}
requests.post('www.baidu.com',json=params) #这里要写json
# 发送的json数据
headers={
"User-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Mobile Safari/537.36 Edg/103.0.1264.71"
}
requests.get('www.baidu.com',headers=headers)
解释:接受服务器返回的内容
前要:response = requests.get('www.baidu.com')
response.text
response.json()
response.content
response.status_code
response.headers
response.cookies #查看数据:类似字典遍历
response.history
参数:
i.jpg
(自定义的文件名字);open('4.jpg','rb')
(选择文件“rb”中b需要写表示二进制读取);'image/jpeg'
(文件类型,服务器可能会验证名字)import requests
url = "http://127.0.0.1:8000/a/go"
files = {
'myfile': ('i.jpg', open('4.jpg', 'rb'), "image/jpeg")
}
response = requests.post(url, files=files)
解释:访问网站后保存下来cookie用于其它操作
参数:
session = requests.Session() #关键操作
import requests
urla = "https://127.0.0.1"
urlb = "https://127.0.0.1/cookie"
data_a={"create_time": 1659171719, "content": "规范化风格恢复鬼画符"}
data_b={"email":"[email protected]","pwd":"1234","remember":True}
session = requests.Session()
response = session.post(urlb, verify=False, json=data_b)
print(response.cookies,response.text)
response_b = session.post(urla, verify=False, json=data_a)
print(response_b.text)
注意:端口以及对应方式一定写对;如果本地代理一定要开全局模式
import requests
urla = "https://127.0.0.1"
urlb = "https://127.0.0.1/cookie"
dataa={"create_time": 1659171800, "content": "规范化风"}
datab={"email":"[email protected]","pwd":"12345678a","remember":True}
session = requests.Session()
proxies={
"http":"http://127.0.0.1:1080",
"https":"https://127.0.0.1:1080"
}
response = session.post(urlb, verify=False, json=datab,proxies=proxies)
print(response.cookies,response.text)
responseb = session.post(urla, verify=False, json=dataa,proxies=proxies)
print(responseb.text)
安装:pip install requests[socks]
proxies={
"http":"socks5://127.0.0.1:1080",
"https":"socks5://127.0.0.1:1080"
}
response = session.post(urlb, verify=False, json=datab,proxies=proxies)