一、Requests库的2个重要对象:Response(包含爬虫返回的内容)和Request
Response对象的属性
r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式(
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content HTTP响应内容的二进制形式
get方法获取网上资源的基本流程:用r.status_code检查返回状态 ,
情况1:如果是200,可以用r.text、r.encoding、r.apparent_encoding、r.content解析返回的内容;
情况2:返回的是404或者其他,则访问不成功
r.encoding和r.apparent_encoding的区别
**r.encoding:**如果header中不存在charset,则认为编码为ISO-8859-1
**r.apparent_encoding:**根据网页内容分析出的编码方式
综上所述,r.apparent_encoding比r.encoding更为准确
**r.raise_for_status()**Requests库用于检验异常
爬取网页的通用代码框架
def getHTMLText(url):
try:
r=requests.get(url,timeout30)
r.raise_for_status #如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
return r.text
ecxept:
return #产生异常
保证网络连接的异常能够被有效处理
实例
(1)京东商品页面的爬取
>>> import requests
>>> r = requests.get("http://sale.jd.com/act/L1Y2V6ERZePab4.html?cpdad=1DLSUE")
>>> r.status_code
200
>>> r.encoding
'utf-8'
>>> r.text[:1000]
(2)网络图片的爬取与存储,利用response.content
(二进制格式的图片、动画、视频等都可以爬取)
>>> import requests
>>> path = "E://abc.jpg"
>>> url = "http://p7.qhmsg.com/t0142c4b9ee48e461ed.jpg"
>>> r = requests.get(url)
>>> r.status_code
200
>>> with open(path,'wb') as f:
f.write(r.content)
>>> f.close
<built-in method close of file object at 0x00000000042979C0>