Python爬虫(2.1):Requests和Response的基本用法

安装Requests库

启动cmd控制台, 安装Requests库(pip install requests) 
测试安装效果:启动IDLE

    >>> import requests
    >>> r = requests.get("http://www.baidu.com")
    >>> r.status_code
    200
    >>> r.encoding = 'utf-8'
    >>> r.text
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

成功抓取百度主页

这里写图片描述

Requests库的get()方法

    r = requests.get(url)
  • 1

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

保证网络连接的异常能够被有效处理

网络爬虫的限制

来源审查:判断User-Agent进行限制 
检查来访HTTP协议头的User-agent域,只响应浏览器或者友好爬虫访问 
发布公告Robots协议 
告知所有爬虫网站的爬取策略,要求爬虫遵守

Robots协议基本语法

User-agent:* 
Disallow: / 
* 代表所有 , / 代表根目录


实例

(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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2)亚马逊商品页面的爬取

这里写图片描述
这里写图片描述

(3)360搜索关键词提交

    >>> import requests
    >>> kv = { 'wd':'Python'}
    >>> r = requests.get("http://www.baidu.com/s",params = kv)
    >>> r.status_code
    200
    >>> r.request.url
'http://www.baidu.com/s?wd=Python'
    >>> len(r.text)
    264348
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

(4)网络图片的爬取与存储

(二进制格式的图片、动画、视频等都可以爬取)

    >>> 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

图片则保存在E盘中

(5)IP地址归属地的自动查询

    >>> import requests
    >>> url = 'http://m.ip138.com/ip.asp?ip='
    >>> r.status_code
    200
    >>> r.text[-500:]

猜你喜欢

转载自blog.csdn.net/hzp666/article/details/79963678