python3基础04(requests常见请求)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests
import json
import re
import urllib3
from urllib.parse import urlencode,quote,unquote

url="https://www.baidu.com"
res=requests.get(url)

#响应内容常见字段信息
print(res.text)
print(res.content)
print(res.reason)
print(res.cookies)
print(res.encoding)
print(res.request.headers)
print(res.headers)
print(res.url)
print(res.history)
print(res.raise_for_status())
print(res.raw)
print(res.json())

#发送params参数get请求
url='https://www.baidu.com'
params={'key1':'value1','key2':'value2'}
res1=requests.get(url,params=params)
print(res1.status_code)

#发送params参数post请求
res2=requests.post(url,data=params)

#发送带headers的get请求
host="http://192.168.1.133:8082/login?from=%2F"
endpoint="get"
url=''.join([host,endpoint])

params={"key1":'value1'}
headers={"User-Agent":"agent1",'Accept': '*/txt'}

res=requests.get(url,headers=headers,params=params)

print(res.request.headers)
print(res.url)
print(type(res.text))
print(eval(res.text))

#发送data参数的post请求
username="admin"
password="123456"
url=host+"/security_check"
headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
"Accept-Encoding": "gzip, deflate",
"Content-Type": "application/x-www-form-urlencoded",
"Upgrade-Insecure-Requests": "1"}

payload={"username":username,"password":password,"from":"/","Submit":"登录"}

res=requests.post(url,headers=headers,data=payload)
result=res.content.decode("utf-8")
print(result)

#unquote的使用
url3="http://www.baidu.com"
param={"username1":"name1","realname1":"好好1"}
body={"username2":"name2","realname2":"好好2"}

res=requests.post(url3, params=param, data=body)
print(res.url)
print(unquote(res.url))

转载于:https://www.cnblogs.com/NiceTime/p/10070287.html

你可能感兴趣的:(json,xhtml,python)