1、最基本的网页响应访问
import requests
#url为网页地址
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
res=requests.get(url=url)
print(res.status_code)
print(res.text)
2、定制header模拟浏览器访问
import requests
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"}
res=requests.get(url=url,headers=header)
result=res.text
print(result)
print(res.headers)
3、post参数传递
import requests
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"}
postData={"username":"admin","password":"admin"}
res=requests.get(url=url,headers=header,data=postData)
print(res.url)
print(res.text)
4、文件上传
import requests
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"}
postData={"userSubmit":"submit"}
upFile={"userUpFile":open("test.txt","rb")}
res=requests.get(url=url,headers=header,file=upFile,data=postData)
print(res.url)
print(res.text)
5、get传参
import requests
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"}
getPara={"username":"admin","password":"admin"}
res=requests.get(url=url,headers=header,params=getPara)
print(res.url)
print(res.text)
6、Request方法:
requests.request(method, url, **kwargs)
import requests
url="https://www.cnblogs.com/lanyinhao/p/9634742.html"
kv={'key1':'value1',"key2":"value2"}
re=requests.request('GET',url,params=kv)
re=requests.request('HEAD',url,params=kv)
re=requests.request('POST',url,params=kv)
re=requests.request('PUT',url,params=kv)
re=requests.request('PATCH',url,params=kv)
re=requests.request('DELETE',url,params=kv)
re=requests.request('OPTIONS',url,params=kv)
re=requests.request('POST',url,data=kv)
body="内容"
re=requests.request('POST',url,data=body)
header={"user-agent":"Chrome/10"}
re=requests.request('POST',url,headers=header)
fs={"file":open('data.txt','rb')}
re=requests.request('POST',url,files=fs)
print(re.url)
7、requests方法
方法 | 说明 |
requests.request() | 构造一个请求,支撑一下各方法的基础方法 |
requests.get() | 获取HTML网页的主要方法,对应于HTTP的GET |
requests.head() | 获取HTML网页头信息的方法,对应于HTTP的HEAD |
requests.post() | 向HTML网页提交POST请求的方法,对应于HTTP的POST |
requests.put() | 向HTML网页提交PUT请求的方法,对应于HTTP的PUT |
requests.patch() | 向HTML网页提交局部修改请求,对应于HTTP的PATCH |
requests.delete() | 向HTML页面提交删除请求,对应于HTTP的DELETE |
8、