获得网站管理员密码,网站开发调查问卷题,做网站建设挣钱吗,关键词搜索查找工具简介 Requests是用python语言基于urllib编写的#xff0c;采用的是Apache2 Licensed开源协议的HTTP库#xff0c;Requests它会比urllib更加方便#xff0c;可以节约我们大量的工作。
一、安装 pip快速安装#xff1a;pip install requests
二、使用
import requestsresp…简介 Requests是用python语言基于urllib编写的采用的是Apache2 Licensed开源协议的HTTP库Requests它会比urllib更加方便可以节约我们大量的工作。
一、安装 pip快速安装pip install requests
二、使用
import requestsresponse requests.get(https://www.baidu.com)
print(type(response))
print(response.status_code)
print(type(response.text))response.enconding utf-8
print(response.text)print(response.cookies)print(response.content)
print(response.content.decode(utf-8))
response.text返回的是Unicode格式通常需要转换为utf-8格式否则就是乱码。response.content是二进制模式可以下载视频之类的如果想看的话需要decode成utf-8格式。 不管是通过response.content.decode(utf-8)的方式还是通过response.encodingutf-8的方式都可以避免乱码的问题发生
2、一大推请求方式
import requests
requests.post(http://httpbin.org/post)
requests.put(http://httpbin.org/put)
requests.delete(http://httpbin.org/delete)
requests.head(http://httpbin.org/get)
requests.options(http://httpbin.org/get)
基本GET:
import requestsurl https://www.baidu.com/
response requests.get(url)
print(response.text) r.encoding #获取当前的编码 r.encoding utf-8 #设置编码 r.text #以encoding解析返回内容。字符串方式的响应体会自动根据响应头部的字符编码进行解码。 r.content #以字节形式二进制返回。字节方式的响应体会自动为你解码 gzip 和 deflate 压缩。 r.headers #以字典对象存储服务器响应头但是这个字典比较特殊字典键不区分大小写若键不存在则返回None r.status_code #响应状态码 r.raw #返回原始响应体也就是 urllib 的 response 对象使用 r.raw.read() r.ok # 查看r.ok的布尔值便可以知道是否登陆成功 #*特殊方法*# r.json() #Requests中内置的JSON解码器以json形式返回,前提返回的内容确保是json格式的不然解析出错会抛异常 r.raise_for_status() #失败请求(非200响应)抛出异常 带参数的GET请求 如果想查询http://httpbin.org/get页面的具体参数需要在url里面加上例如我想看有没有Hosthttpbin.org这条数据url形式应该是http://httpbin.org/get?Hosthttpbin.org 下面提交的数据是往这个地址传送data里面的数据。
import requestsurl http://httpbin.org/get
data {name:zhangsan,age:25
}
response requests.get(url,paramsdata)
print(response.url)
print(response.text)#URL传递参数
payload {keyword: 香港, salecityid: 2}
r requests.get(http://m.ctrip.com/webapp/tourvisa/visa_list, paramspayload)
printr.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid2keyword香港
POST请求
# 1、基本POST实例import requestspayload {key1: value1, key2: value2}
ret requests.post(http://httpbin.org/post, datapayload)print(ret.text)# 2、发送请求头和数据实例import requests
import jsonurl https://api.github.com/some/endpoint
payload {some: data}
headers {content-type: application/json}ret requests.post(url, datajson.dumps(payload), headersheaders)print(ret.text)
print(ret.cookies) https://cuiqingcai.com/2556.html
https://www.cnblogs.com/lei0213/p/6957508.html
https://www.cnblogs.com/lei0213/p/6957508.html