码迷,mamicode.com
首页 > 其他好文 > 详细

网络爬虫--requests库中两个重要的对象

时间:2017-10-19 21:02:58      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:odi   http   状态   连接   exce   for   _for   方式   return   

当我们使用resquests.get()时,返回的时response的对象,他包含服务器返回的所有信息,也包含请求的request的信息。 
首先: 
response对象的属性有以下几个, 
r.status_code是http请求的返回状态,200表示连接成功,404表示连接失败,这时候应该抛出异常,进行处理。 
r.text是url对应的页面内容 
r.encoding是从http的header中猜测的响应内容编码方式 
r.apparent_encoding是从内容中分析出响应的内容编码方式。 
r.content是http响应内容的二进制形式

通用的代码框架

try: 
    r=requests.get(url,timeout=30) 
    r.raise_for_status()#如果不是200,就会抛出异常 
    r.encoding=r.apparent_encoding 
    return r.text 
except: 
    return “产生异常”

网络爬虫--requests库中两个重要的对象

标签:odi   http   状态   连接   exce   for   _for   方式   return   

原文地址:http://www.cnblogs.com/freeman818/p/7694607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!