Request库的7个主要方法:

requests.request(method,url,**kwargs)
  • ​ method:请求方式,对应get/put/post等7种;

​ r = requests.request('GET',url,**kwargs)

​ r = requests.request('HEAD',url,**kwargs)

​ ......

  • ​ url:拟获取页面的url链接;
  • ​ **kwargs:控制访问的参数,共13个;均为可选项
  1. ​ params : 字典或字节序列,作为参数增加到url中;
  2. ​ data : 字典、字节序列或文件对象,作为Request的内容
  3. ​ json : JSON格式的数据,作为Request的内容;
  4. ​ headers :字典,HTTP定制头;
  5. ​ cookies :字典或CookieJar、Request中的cookie;
  6. ​ auth:元组,支持HTTP认证功能;
  7. ​ files : 字典类型,传输文件;
  8. ​ timeout :设定超时时间,秒为单位;
  9. ​ proxies : 字典类型,设定访问代理服务器,可以增加登录认证;
  10. ​ allow_redirects : True/False,默认为True,重定向开关;
  11. ​ stream: True/False,默认为True,获取内容立即下载开关;
  12. ​ verify : True/False,默认为True,认证SSL证书开关;
    1. ​ cert : 本地SSL证书路径;

       requests.get(url,params = None,**kwargs)
      
       requests.head(url,**kwargs)
      
       requests.post(url,data = None,params = None,**kwargs)
      
       requests.put(url,data = None,**kwargs)
      
       requests.patch(url,data = None,**kwargs)
      
       requests.delete(url,**kwargs)
      
       requests.get(url,params = None,**kwargs)

      url : 拟获取页面的url链接;

      ​ params :url中的额外参数,字典或字节流格式,可选;

      ​ **kwargs :12个控制访问的参数;

      r = requests.get(url)

      Response对象包含爬虫返回的内容 

Response对象的属性:

理解Request库的异常:

r.raise_for_status() 如果不是200,产生异常 requests.HTTPError

HTTP(Hypertext Transfer Protocol)协议:超文本传输协议。

​ HTTP是一个基于“请求与响应”模式的、无状态的应用层协议;

​ HTTP协议采用URL作为定位网络资源的标识,URL格式如下:

http://host:[port][path]

​ host : 合法的Internet主机域名或IP地址;

​ port : 端口号,缺省端口为80;

​ path : 请求资源的路径。

HTTP协议对资源的操作:

通过URL和命令管理资源,操作无独立状态,网络通道及服务器成为了黑盒子。

理解PATCH和PUT的区别:

假设URL位置有一组数据UserID、UserName等20个字段。

需求:用户修改了UserName,其他不变。

​ 采用PATCH,仅向URL提交UserName的局部更新请求;

​ 采用PUT,必须将所有20个字段一并提交到URL,未提交字段被删除。

PATCH最主要的好处:节省网络带宽。

HTTP协议与Requests库:

实例1:京东商品页面的爬取。

网址:http://item.jd.com/2967929.html

>>> import requests
>>> r = requests.get("http://item.jd.com/2967929.html")
>>> r.status_code
200
>>> r.encoding
'gbk'
>>> r.text[:1000]
'<!DOCTYPE HTML>\n<html lang="zh-CN">\n<head>\n   <!-- shouji -->\n   <meta http-equiv="Content-Type" content="text/html; charset=gbk" />\n   <title>【华为荣耀8】【新年货】荣耀8 4GB+64GB 全网通4G手机 魅海蓝【行情 报价 价格 评测】-京东</title>\n   <meta name="keywords" content="HUAWEI荣耀8,华为荣耀8,华为荣耀8报价,HUAWEI荣耀8报价"/>\n   <meta name="description" content="【华为荣耀8】京东JD.COM提供华为荣耀8正品行货,并包括HUAWEI荣耀8网购指南,以及华为荣耀8图片、荣耀8参数、荣耀8评论、荣耀8心得、荣耀8技巧等信息,网购华为荣耀8上京东,放心又轻松" />\n   <meta name="format-detection" content="telephone=no">\n   <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/2967929.html">\n   <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/2967929.html">\n   <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n   <link rel="canonical" href="//item.jd.com/2967929.html"/>\n       <link rel="dns-prefetch" href="//misc.360buyimg.com"/>\n   <link rel="dns-prefetch" href="//static.360buyimg.com"/>\n   <link rel="dns-prefetch" href="//img10.360buyimg.com"/>\n   <link rel'

全代码:

#jd code.py
import requests
url = "http://item.jd.com/2967929.html"
try:
   r = requests.get(url)
   r.raise_for_status()
   r.encoding = r.apparent_encoding
   print(r.text[:1000])
except:
   print("爬取失败")

限制是否能爬虫的两种方式:robots协议、判断http的头是否为浏览器;

实例2:亚马逊商品页面的爬取。

网址:http://www.amazon.cn/gp/product/B01M8L5Z3Y

>>> import requests     #引入库
>>> r = requests.get("http://www.amazon.cn/gp/product/B01M8L5Z3Y")
>>> r.status_code #读取返回状态
200
>>> r.encoding #查看编码
'UTF-8'
>>> r.request.headers #读取http的头
{'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
>>> kv = {'user-agent':'Mozilla/5.0'} #构造键值对,模拟浏览器;
#'Mozilla/5.0'是很标准的浏览器的身份标识字段
>>> url = "http://www.amazon.cn/gp/product/B01M8L5Z3Y"
>>> r = requests.get(url,headers = {'user-agent':'Mozilla/5.0'})
#模拟浏览器访问网址
>>> r.status_code
200
>>> r.request.headers #验证结果,头部被修改
{'user-agent': 'Mozilla/5.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
>>> r.text[:1000]
'\n\n\n\n\n\n\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n   \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n   \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n   \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n   <!doctype html><html class="a-no-js" data-19ax5a9jf="dingo">\n   <head>\n<script type="text/javascript">var ue_t0=ue_t0||+new Date();</script>\n<script type="text/javascript">\n\nvar ue_hob=+new Date();\nvar ue_id=\'66XSFDDTW64FMKQK42YQ\',\nue_csm = window,\nue_err_chan = \'jserr-rw\',\nue = {};\n(function(d){var e=d.ue=d.ue||{},f=Date.now||function(){return+new Date};e.d=function(b){return f()-(b?0:d.ue_t0)};e.stub=function(b,a){if(!b[a]){var c=[];b[a]=function(){c.push([c.slice.call(arguments),e.d(),d.ue_id])};b[a].replay=function(b){for(var a;a=c.shift();)b(a[0],a[1],a[2])};b[a].isStub=1}};e.exec=function(b,a){return function(){if(1==window.ueinit)try{return b.apply(this,arguments)}catch(c){ueLogError(c,{attribution:a||"undefined",logLevel:"WARN"})}}}})(ue_csm);\n\nue.stub(ue,"log");ue.stub(ue,"onunload");ue.stub(ue,"onflush");\n\n(function(d,e){function h(f,b){if(!(a.ec>a.mxe)&&f){a.ter.pu'

全代码:

#amazon code.py
import requests
url = "http://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("爬取失败")

实例3:百度网页爬取。

>>> 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)
312484

全代码:

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

实例4:360浏览器网页爬取。

>>> import requests
>>> kv = {'q':'Python'}
>>> r = requests.get("http://www.so.com/s",params = kv)
>>> r.status_code
200
>>> r.request.url
'https://www.so.com/s?q=Python'
>>> len(r.text)
275843

全代码:

#360 code.py
import requests
keyword = "python"
try:
   kv = {'q':'Python'}
   r = requests.get("http://www.so.com/s",params = kv)
   print(r.request.url)
   r.raise_for_status()
   print(len(r.text))
except:
   print("爬取失败")

实例5:网络图片的爬取和存储。

图片地址:http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg

代码:

#picture code.py
import requests
import os
url = "http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg"
#root = "C:/Users/E5-573G/Desktop/2018寒假/python/爬虫/图"   #正常运行,不会出错。绝对路径用/
#root = "C:\Users\E5-573G\Desktop\2018寒假\Python\爬虫\图"   出现Unicode Error 错误,\转义的放式
root = r"C:\Users\E5-573G\Desktop\2018寒假\Python\爬虫\图"   #正常运行,不会出错。r\不需要转义
path = root + url.split('/')[-1]
try:
   if not os.path.exists(root):
       os.mkdir(root)
   if not os.path.exists(path):
       r = requests.get(url)
       with open(path,'wb') as f:
           f.write(r.content)
           f.close
           print("文件保存成功")
   else:
       print("文件已存在")
except:
   print("爬取失败")

利用爬虫在淘宝网上查找“python web”向相关的商品:

#Crow TaobaoPrice.py
import requests
import re def getHTMLText(url):
   try:
       r = requests.get(url, timeout=30)
       r.raise_for_status()
       r.encoding = r.apparent_encoding
       return r.text
   except:
       return ""
   
def parsePage(ilt, html):
   try:
       plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
       tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
       for i in range(len(plt)):
           price = eval(plt[i].split(':')[1])
           title = eval(tlt[i].split(':')[1])
           ilt.append([price , title])
   except:
       print("") def printGoodsList(ilt):
   tplt = "{:4}\t{:8}\t{:16}"
   print(tplt.format("序号", "价格", "商品名称"))
   count = 0
   for g in ilt:
       count = count + 1
       print(tplt.format(count, g[0], g[1]))
       
def main():
   goods = 'python web'
   depth = 3
   start_url = 'https://s.taobao.com/search?q=' + goods
   infoList = []
   for i in range(depth):
       try:
           url = start_url + '&s=' + str(44*i)
           html = getHTMLText(url)
           parsePage(infoList, html)
       except:
           continue
   printGoodsList(infoList)
   
main()

运行结果:

爬虫request库规则与实例的更多相关文章

  1. 爬虫——urllib.request库的基本使用

    所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地.在Python中有很多库可以用来抓取网页,我们先学习urllib.request.(在python2.x中为urllib2 ...

  2. Python网络爬虫与信息提取[request库的应用](单元一)

    ---恢复内容开始--- 注:学习中国大学mooc 嵩天课程 的学习笔记 request的七个主要方法 request.request() 构造一个请求用以支撑其他基本方法 request.get(u ...

  3. Python爬虫——request实例:爬取网易云音乐华语男歌手top10歌曲

    requests是python的一个HTTP客户端库,跟urllib,urllib2类似,但比那两个要简洁的多,至于request库的用法, 推荐一篇不错的博文:https://cuiqingcai. ...

  4. Python request库与爬虫框架

    Requests库的7个主要方法  requests.request():构造一个请求,支持以下各方法的基础方法  requests.get():获取HTML网页的主要方法,对应于HTTP的GET  ...

  5. 爬虫基本库request使用—爬取猫眼电影信息

    使用request库和正则表达式爬取猫眼电影信息. 1.爬取目标 猫眼电影TOP100的电影名称,时间,评分,等信息,将结果以文件存储. 2.准备工作 安装request库. 3.代码实现 impor ...

  6. Python爬虫urllib库的使用

    urllib 在Python2中,有urllib和urllib2两个库实现请求发送,在Python3中,统一为urllib,是Python内置的HTTP请求库 request:最基本的HTTP请求模块 ...

  7. Python3 urllib.request库的基本使用

    Python3 urllib.request库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 在Python中有很多库可以用来抓取网页,我们先学习urlli ...

  8. [python爬虫]Requests-BeautifulSoup-Re库方案--Requests库介绍

    [根据北京理工大学嵩天老师“Python网络爬虫与信息提取”慕课课程编写  文章中部分图片来自老师PPT 慕课链接:https://www.icourse163.org/learn/BIT-10018 ...

  9. Python爬虫Urllib库的基本使用

    Python爬虫Urllib库的基本使用 深入理解urllib.urllib2及requests  请访问: http://www.mamicode.com/info-detail-1224080.h ...

随机推荐

  1. ISO/IEC 9899:2011 条款6.7.4——函数说明符

    6.7.4 函数说明符 语法 1.function-specifier: inline _Noreturn 约束 2.函数说明符应该只能被用在对一个函数标识符的声明中. 3.对一个含有外部连接函数的内 ...

  2. ubuntu 防火墙打开关闭

    1.查看防火墙状态 sudo ufw status 2.打开防火墙 sudo ufw enable 3.关闭防火墙 sudo ufw disable

  3. 123457123457#0#-----com.tym.YuErBaiKeTYM--前拼后广--育儿百科

    com.tym.YuErBaiKeTYM--前拼后广--育儿百科

  4. vs2010 出错:error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏(转)

    “LNK1123:转换到 COFF期间失败:文件无效或损坏”的解决方法 一.错误描述 之前写的程序隔段时间使用VS2010再次运行时出现如下错误: LINK fatal error LNK1123转换 ...

  5. PLSQL集合类型的使用总结

    PLSQL集合类型的使用总结 在pl sql 中,集合(collection) 是一组有序的元素组成的对象,这些元素的类型必须一致. pl sql 将collection 分成3 类,分别为Assoc ...

  6. ubuntu18.04手动安装二进制MySQL8.0

    wget https://cdn.mysql.com//Downloads/MySQL-8.0/mysql-8.0.13-linux-glibc2.12-x86_64.tar.xz tar xvJf ...

  7. redis 队列模式

    1.插入队列(生产者) private static RedisClient client = new RedisClient("127.0.0.1", 6379, null);c ...

  8. 【译】Vue源码学习(一):Vue对象构造函数

    本系列文章详细深入Vue.js的源代码,以此来说明JavaScript的基本概念,尝试将这些概念分解到JavaScript初学者可以理解的水平.有关本系列的一些后续的计划和轨迹的更多信息,请参阅此文章 ...

  9. Apache Shiro初认识

    Apache Shiro 一.Shiro介绍: Apache软件基金会专门针对系统中的登录.加密.权限认证.授权等等功能进行了封装,不仅仅适用于JavaWeb项目,CS架构的系统也可以使用Shiro. ...

  10. Visual Studio Code 中实现 C++ 函数定义跳转和代码自动补全功能(25)

    方法1: 1.1 安装插件 C++ Intellisense 名称: C++ Intellisense id: austin.code-gnu-global 说明: C/C++ Intellisens ...