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

来源:互联网 发布:淘宝买白酒是真的吗 编辑:程序博客网 时间:2024/05/18 12:44

当我们使用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 “产生异常”

0 0