【python第三方库】requests库爬虫入门

参考链接: https://blog.csdn.net/qq_37098526/article/details/94207603

概述

requests 库是一个简洁且简单的处理HTTP请求的第三方库。

requests的最大优点是程序编写过程更接近正常URL 访问过程。

这个库建立在Python 语言的urllib3 库基础上,类似这种在其他函数库之上再封装功能提供更友好函数的方式在Python 语言中十分常见。在Python 的生态圈里,任何人都有通过技术创新或体验创新发表意见和展示才华的机会。

request 库支持非常丰富的链接访问功能,包括:国际域名和URL 获取、HTTP 长连接和连接缓存、HTTP 会话和Cookie 保持、浏览器使用风格的SSL 验证、基本的摘要认证、有效的键值对Cookie 记录、自动解压缩、自动内容解码、文件分块上传、HTTP(S)代理功能、连接超时处理、流数据下载等。

有关requests 库的更多介绍请访问:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

具体介绍

Requests库的主要方法

在这里插入图片描述

request方法:向url页面构造一个请求,其余六种方法通过调用封装好的request函数来实现的

表中对应HTTP的操作如下:
HTTP:超文本传输协议,一个基于请求与响应模式的、无状态的应用层协议,采用URL作为定位网络资源的标识。

URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源,格式:http://host[:port][path]

  • host:合法的Internet主机域名或IP地址
  • port:端口号,缺省端口为80
  • path:请求资源的路径

HTTP协议对资源的操作
在这里插入图片描述

HTTP协议与Requests库的方法是一一对应的。

1. requests.get()方法

r=requests.get(url,params=None,**kwargs)

  • url:拟获取页面的url链接
  • params:url中的额外参数,字典或字节流格式,可选
  • **kwargs:12个控制访问的参数
    在这里插入图片描述

2. Requests库的head()方法

在这里插入图片描述

3. Requests库的post()方法(附加新的数据)

在这里插入图片描述

4. Requests库的put()方法(覆盖原有数据)

在这里插入图片描述

requests.requests(method,url,**kwargs)

**kwargs:控制访问的参数,均为可选项:

  • params:字典或字节序列,作为参数增加到url中
    在这里插入图片描述
  • data:字典、字节序列或文件对象,作为Request的内容
    在这里插入图片描述
  • json:JSON格式的数据,作为Request的内容
    在这里插入图片描述
  • headers:字典,HTTP定制头(模拟pc端浏览器身份,不设置headers就是python身份发出的请求,一般都会被禁掉)
    在这里插入图片描述
  • cookies:字典或CookieJar,Request中的cookie
  • auth:元组,支持HTTP认证功能
  • files:字典类型,传输文件
    在这里插入图片描述
  • timeout:设定超时时间,秒为单位
    在这里插入图片描述
  • proxies:字典类型,设定访问代理服务器,可以增加登录认证
    在这里插入图片描述

Response对象属性

Requests库的2个重要对象:
在这里插入图片描述
在这里插入图片描述

Response对象包含服务器返回的所有信息,同时也包含向服务器请求的Request信息。

Response对象属性
在这里插入图片描述

  • r.encoding:如果header中不存在charset,则认为编码为ISO‐8859‐1(这种编码并不能解析中文!!!)

  • r.text:根据r.encoding显示网页内容

  • r.apparent_encoding:根据网页内容分析出的编码方式可以看作是r.encoding的备选

原则上来说其实apparent_encoding编码方式比encoding更为准确,encoding并没有分析内容,只是从header相关字段中提取编码数,而apparent_encoding却是实实在在分析内容,并且找到可能的编码。

Requests库的异常

在这里插入图片描述
raise_for_status()方法:

raise_for_status()方法能在非成功响应后产生异常,即只要返回的请求状态status_code 不是200,这个方法会产生一个异常,用于try…except 语句。

使用异常处理语句可以避免设置一堆复杂的if 语句,只需要在收到响应调用这个方法,就可以避开状态字200以外的各种意外情况。

代码示例

通用框架

import requests
def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()  # 如果状态不是200, 引发HTTPError异常
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "产生异常"

if __name__=="__main__":
    url = "http://www.baidu.com"
    print(getHTMLText(url))

京东商品页面爬取

import requests
url = 'https://item.jd.com/100004404944.html'
try:
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失败")

在这里插入图片描述

亚马逊商品页面的提取

import requests
url = 'https://www.amazon.cn/gp/product/B01M8L5Z3Y'
try:
    kv = {'User-Agent':'Mozilla/5.0'}
    r = requests.get(url, headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[1000:2000])
except:
    print("爬取失败")

这里通过headers字段模拟浏览器向亚马逊服务器提供HTTP请求。

在这里插入图片描述

百度360搜索关键词提交

百度的关键词接口:http://www.baidu.com/s?wd=keyword

360的关键词接口:http://www.so.com/s?q=keyword

import requests
keyword = 'python'
try:
    kv = {'wd':keyword}
    r = requests.get("http://www.baidu.com/s", params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失败")

在这里插入图片描述

网络图片的爬取和存储

网络图片链接的格式:http://www.example.com/picture.jpg

国家地理:http://www.ngchina.com.cn/

选择一个图片Web页面:http://www.ngchina.com.cn/photography/photo_of_the_day/5946.html

图片链接:http://image.ngchina.com.cn/2019/0629/20190629042347347.jpg

import requests
import os
url = 'http://image.ngchina.com.cn/2019/0629/20190629042347347.jpg'
root = 'D://pics//'
path = root + url.split('/')[-1]  # 以jpg图片名字作为文件名
try:
    if not os.path.exists(root):
        os.mkdir(root)  # 当文件夹不存在时创建root文件夹
    if not os.path.exists(path):
        r = requests.get(url)  # 当jpg图片名文件不存在时爬取该图片
        with open(path, 'wb') as f:
            f.write(r.content)
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")

IP地址归属地的自动查询

在这里插入图片描述
接口形式:http://m.ip138.com/ip.asp?ip=ipaddress

import requests
url = 'http://m.ip138.com/ip.asp?ip='
try:
    r = requests.get(url+'106.39.41.16')
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[-500:])
except:
    print("爬取失败")

在这里插入图片描述

爬取国外船只网站图片

#coding=utf-8
import re
import requests


if __name__ =='__main__':

    save_dir = 'F:/public_dataset/PHFV_Detect_Samples/shipspotting2/'

    for i in range(0,1):
        url = 'http://www.shipspotting.com/gallery/photo.php?lid=%d' % i
        print(url)
        try:
            result = requests.get(url)
            #print(result.status_code)
            find_pic=result.text
            pic_url = re.findall('http://www.shipspotting.com/photos/middle.*?.jpg', find_pic, re.S)

            for each in pic_url:
                try:
                    if each is not None:
                        pic = requests.get(each)
                    else:
                        continue
                except BaseException:
                    print(u'error')
                    continue
                else: # try块语句无异常时执行else
                    string = save_dir + str(i) + '.jpg'
                    fp = open(string, 'wb')
                    fp.write(pic.content)
                    fp.close()
        except:
            continue


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值