介绍
这篇文章主要介绍了response.content和response.text的区别,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。
1。response.content和response.text的区别
response.content是编码后的字节类型(“str”数据类型),响应。文本是unicode类型。这两种方法的使用要视情况而定。注意:unicode→str是编码过程(编码());str→unicode是解码过程(decode()),示例如下:
#,——编码:utf - 8——# import 请求 时间=response requests.get (“https://baidu.com/") print response.url print 类型(response.content) with 开放(“C: \ \ \ \ \ \用户管理员桌面\ \ content.html",,“w"), as f: ,,,f.write (response.content) ,,,print “内容保存成功”; print 类型(response.text) with 开放(“C: \ \ \ \ \ \用户管理员桌面\ \ text.html",,“w"), as f: ,,,#,返回url的编码方式 ,,,print response.encoding ,,,f.write (response.text.encode (“iso - 8859 - 1 -“)) ,,,print “文本保存成功“
2。发送得到请求,直接调用“resquests.get"就可以了.response的一些属性:response.text;response.content;response.url;response.encoding;响应。status_code
#,——编码:utf - 8——# import 请求 params =, { ,,,“wd":,“中国“; } headers =, { ,,,“User-Agent":,“Mozilla/5.0, (Windows NT 6.1;, Win64;, x64), AppleWebKit/537.36, (KHTML, like 壁虎),Chrome/67.0.3396.62 Safari/537.36“ } response =, requests.get (“https://baidu.com/s",, params=params,标题=标题) print response.url with 开放(“C: \ \ \ \ \ \用户管理员桌面\ \ get.html",,“w"), as f: ,,,f.write (response.content) ,,,print “保存成功“
3。发送帖子请求:传入数据信息。注意得到请求传入的是参数信息。示例如下:
#,——编码:utf - 8——# import 请求 data =, { ,,,“至上”:,“true" ,,,“pn":,“1”, ,,,“wd":,“python" } headers =, { ,,,“Referer":,“https://www.lagou.com/jobs/list_python?labelWords=& fromSearch=true& suginput=? ,,,“User-Agent":,“Mozilla/5.0, (Windows NT 6.1;, Win64;, x64), AppleWebKit/537.36, (KHTML, like 壁虎),Chrome/67.0.3396.62 Safari/537.36“ } 时间=response requests.post (“https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false",, data=https://www.yisu.com/zixun/data,头=标题) 打印response.encoding 打印类型(response.content) 张开(“C://用户/管理员//桌面//职位。html”、“w”) f: f.write (response.content) 打印”保存成功”
4。使用代理。在得到方法中增加代理参数即可。示例代码如下:
#,——编码:utf - 8——# import 请求 proxy =, { ,,,“http":,“124.42.7.103" } 时间=response requests.get (“http://httpbin.org/ip",,代理=代理) print response.content
5。请求处理饼干信息。使用requests.Session()方法即可。示例代码如下:
#,——编码:utf - 8——# import 请求 时间=url “http://www.renren.com/PLogin.do"=#,url “http://www.renren.com/SysHome.do" data =, {“email":,“账号“,,“password":,“密码“} headers =, { ,,,“User-Agent":,“Mozilla/5.0, (Windows NT 6.1;, Win64;, x64), AppleWebKit/537.36, (KHTML, like 壁虎),Chrome/67.0.3396.62 Safari/537.36“ } 时间=session requests.Session () session.post (url, data=https://www.yisu.com/zixun/data,标题=标题) 响应=session.get (“http://www.renren.com/543484094/profile”) 张开(“C://用户/管理员//桌面//人力资源。html”、“w”)作为外交政策: fp.write (response.content) 打印”保存成功”
6。处理不信任的SSL证书。与上面的代码相比,多了一个验证=False参数,为了处理SSL证书不受信用的问题。
示例代码如下:
response =, session.get (“http://www.renren.com/543484094/profile",,验证=False)
感谢你能够认真阅读完这篇文章,希望小编分享的“response.content和response.text的区别”这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!