python3 requests模块_python3 爬虫之requests模块使用总结

Requests 是第三方模块,如果要使用的话需要导入。Requests也可以说是urllib模块的升级版,使用上更方便。

这是使用urllib的例子。

importurllib.requestimportjson

url= ‘http://www.weather.com.cn/data/sk/101190408.html‘res= urllib.request.urlopen(url)#发送请求

result = res.read().decode()#获取结果,结果是byte类型的需要decode()

print(json.loads(result))

下面是Requests 模块的使用。

支持的请求:

requests.get(‘https://github.com/timeline.json’) #GET请求

requests.post(“http:xxx.xx.com/post”) #POST请求

requests.put(“http:xxx.xx.com/put”) #PUT请求

requests.delete(“http:xxx.xx.com/delete”) #DELETE请求

requests.head(“http:xxx.xx.com/head”) #HEAD请求

requests.options(“http:xxx.xx.com/get”) #OPTIONS请求

发送GET请求:

importrequests,json

url= ‘http://api.xx.cn/api/user/stu_info?stu_name=hi‘req= requests.get(url)#发送get请求

print(req.text)#获取结果直接返回的就是json串

print(type(req.text)) #str

print(json.loads(req.text))#json转字典

print(req.json())#获取结果就是字典,只有返回的是json串的话才能用req.json()

print(type(req.json()))#dict

发送POST请求

url = ‘http://api.xxx.cn/api/user/login‘data= {‘username‘:‘aa‘,‘passwd‘:‘123‘}

req= requests.post(url,data)#发送post请求,第一个参数是url,第二个参数是请求的数据

print(req.json())

发送格式为json的数据

url = ‘http://api.xxx.cn/api/user/add_stu‘data={"name":"aa","grade":"bb","phone":13512530000,

}

req= requests.post(url,json=data)#发送post请求,第一个参数是url,第二个参数是请求的数据,发送的json的话就写json=data

print(req.json())

发送带cookie的请求

url = ‘http://api.xx.cn/api/user/gold_add‘data= {‘stu_id‘:231,‘gold‘:‘100‘}

cookie= {‘aa‘:‘3d867b361afdaac1381b02ae746c7278‘}#key 为登陆的用户名,value为sign的值

req = requests.post(url,data,cookies=cookie)#添加cookie

print(req.json())

发送的请求中带Header

url = ‘http://api.xxx.cn/api/user/all_stu‘header= {‘User-Agent‘:‘Chrome‘}

req= requests.get(url,headers =header)print(req.json())

上传文件

url = ‘http://api.xxx.cn/api/file/file_upload‘f= open(r‘D:\aa.jpg‘,‘rb‘)#图片要指定以二进制方式打开

r =requests.post(url,files={‘file‘:f})print(r.json())

下载文件,图片,视频

url = ‘https://images2017.cnblogs.com/blog/412654/201712/412654-20171213115213238-464712233.png‘r=requests.get(url)print(r.status_code)#获取请求状态码

print(r.content)#获取返回结果二进制格式的

fw = open(‘bt.jpg‘,‘wb‘)#当前路径#fw = open(r‘d:\bt.jpg‘,‘wb‘)#指定绝对路径

fw.write(r.content)#将二进制格式内容写入文件

fw.close()

爬虫,把网页保存到本地

url = ‘http://www.cnblogs.com/nancyzhu/p/8029994.html‘r=requests.get(url)

f= open(‘page.html‘,‘wb‘)

f.write(r.content)

f.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值