[root@node-2 ~]# pip3 install requests
#!/usr/bin/python3
import requests
url = 'http://www.baidu.com'
response = requests.get(url)
print(response)
print(response.status_code)
#这里response 的结果是状态码和准确的状态码
[root@node-2 ~]# ./test.py
<Response [200]>
200
此结果打印出来的中文乱码,如果字符集不是utf-8的就会乱码
response = requests.get(url)
response.encoding = 'utf-8'
print(response.text)
print (response.encoding)
[root@node-2 ~]# ./test.py
ISO-8859-1
decode将content文本流转换成了utf-8.(解码)
print (response.content.decode('utf-8'))
print(response.request.headers)
在本机安装了nginx服务。
自定义了日志格式,这里引用了python客户端自定义的header name和age
log_format main '$remote_addr - $status - $http_user_agent $http_name $http_age';
引用一下自定义格式的日志
access_log logs/access.log main;
url = 'http://127.0.0.1'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
"name": "zhangsan",
"age": "100"
}
response = requests.get(url,headers=headers)
print(response.content.decode('utf-8'))
请求结果:这里看到了自定义封装的header头部中的3个参数
127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
127.0.0.1 - 200 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 zhangsan 100
data就是传递给服务器的参数
import requests
url = 'http://127.0.0.1'
params = {
"username": "zhangsan",
"password": "123"
}
response = requests.post(url,data=params)