25-1 request模块介绍

requests模块

- 基于如下5点展开requests模块的学习

  • 什么是requests模块

    • requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求。功能强大,用法简洁高效。在爬虫领域中占据着半壁江山的地位。
  • 为什么要使用requests模块
    • 因为在使用urllib模块的时候,会有诸多不便之处,总结如下:

      • 手动处理url编码
      • 手动处理post请求参数
      • 处理cookie和代理操作繁琐
      • ......
    • 使用requests模块:
      • 自动处理url编码
      • 自动处理post请求参数
      • 简化cookie和代理操作
      • ......
  • 如何使用requests模块
    • 安装:

      • pip install requests
    • 使用流程
      • 指定url
      • 基于requests模块发起请求
      • 获取响应对象中的数据值
      • 持久化存储
  • 通过5个基于requests模块的爬虫项目对该模块进行学习和巩固
    • 基于requests模块的get请求

      • 需求:爬取搜狗指定词条搜索后的页面数据
    • 基于requests模块的post请求
      • 需求:登录豆瓣电影,爬取登录成功后的页面数据
    • 基于requests模块ajax的get请求
    • 基于requests模块ajax的post请求
    • 综合练习
      • 需求:爬取搜狗知乎指定词条指定页码下的页面数据

- 代码展示

  • 需求:爬取搜狗指定词条搜索后的页面数据

    import requests
    import os
    #指定搜索关键字
    word = input(‘enter a word you want to search:‘)
    #自定义请求头信息
    headers={
        ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36‘,
        }
    #指定url
    url = ‘https://www.sogou.com/web‘
    #封装get请求参数
    prams = {
        ‘query‘:word,
        ‘ie‘:‘utf-8‘
    }
    #发起请求
    response = requests.get(url=url,params=param)
    
    #获取响应数据
    page_text = response.text
    
    with open(‘./sougou.html‘,‘w‘,encoding=‘utf-8‘) as fp:
        fp.write(page_text)
  • 需求:登录豆瓣电影,爬取登录成功后的页面数据

    import requests
    import os
    url = ‘https://accounts.douban.com/login‘
    #封装请求参数
    data = {
        "source": "movie",
        "redir": "https://movie.douban.com/",
        "form_email": "15027900535",
        "form_password": "[email protected]",
        "login": "登录",
    }
    #自定义请求头信息
    headers={
        ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36‘,
        }
    response = requests.post(url=url,data=data)
    page_text = response.text
    
    with open(‘./douban111.html‘,‘w‘,encoding=‘utf-8‘) as fp:
        fp.write(page_text)
  • 需求:爬取豆瓣电影分类排行榜 https://movie.douban.com/中的电影详情数据

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import requests
    import urllib.request
    if __name__ == "__main__":
    
        #指定ajax-get请求的url(通过抓包进行获取)
        url = ‘https://movie.douban.com/j/chart/top_list?‘
    
        #定制请求头信息,相关的头信息必须封装在字典结构中
        headers = {
            #定制请求头中的User-Agent参数,当然也可以定制请求头中其他的参数
            ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36‘,
        }
    
        #定制get请求携带的参数(从抓包工具中获取)
        param = {
            ‘type‘:‘5‘,
            ‘interval_id‘:‘100:90‘,
            ‘action‘:‘‘,
            ‘start‘:‘0‘,
            ‘limit‘:‘20‘
        }
        #发起get请求,获取响应对象
        response = requests.get(url=url,headers=headers,params=param)
    
        #获取响应内容:响应内容为json串
        print(response.text)
  • 需求:爬取肯德基餐厅查询http://www.kfc.com.cn/kfccda/index.aspx中指定地点的餐厅数据

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import requests
    import urllib.request
    if __name__ == "__main__":
    
        #指定ajax-post请求的url(通过抓包进行获取)
        url = ‘http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword‘
    
        #定制请求头信息,相关的头信息必须封装在字典结构中
        headers = {
            #定制请求头中的User-Agent参数,当然也可以定制请求头中其他的参数
            ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36‘,
        }
    
        #定制post请求携带的参数(从抓包工具中获取)
        data = {
            ‘cname‘:‘‘,
            ‘pid‘:‘‘,
            ‘keyword‘:‘北京‘,
            ‘pageIndex‘: ‘1‘,
            ‘pageSize‘: ‘10‘
        }
        #发起post请求,获取响应对象
        response = requests.get(url=url,headers=headers,data=data)
    
        #获取响应内容:响应内容为json串
        print(response.text)
     
  • 需求:爬取搜狗知乎指定词条指定页码下的页面数据

    import requests
    import os
    #指定搜索关键字
    word = input(‘enter a word you want to search:‘)
    #指定起始页码
    start_page = int(input(‘enter start page num:‘))
    end_page = int(input(‘enter end page num:‘))
    #自定义请求头信息
    headers={
        ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36‘,
        }
    #指定url
    url = ‘https://zhihu.sogou.com/zhihu‘
    #创建文件夹
    if not os.path.exists(‘./sougou‘):
        os.mkdir(‘./sougou‘)
    for page in range(start_page,end_page+1):
        #封装get请求参数
        params = {
            ‘query‘:word,
            ‘ie‘:‘utf-8‘,
            ‘page‘:str(page)
        }
        #发起post请求,获取响应对象
        response = requests.get(url=url,params=params)
        #获取页面数据
        page_text = response.text
        fileName = word+‘_‘+str(page)+‘.html‘
        filePath = ‘./sougou/‘+fileName
        with open(filePath,‘w‘,encoding=‘utf-8‘) as fp:
            fp.write(page_text)
            print(‘爬取‘+str(page)+‘页结束‘)

原文地址:https://www.cnblogs.com/huningfei/p/9900195.html

时间: 2024-08-30 15:19:09

25-1 request模块介绍的相关文章

网上图书商城项目学习笔记-031图书管理模块介绍及添加图书

一.流程分析 1.图书管理模块介绍 2. 3. 4.添加图书第一步 5.添加图书第二步 二.代码 1.view层 (1)body.jsp 1 <body> 2 <h1 align="center">图书管理</h1> 3 <p align="center"> 4 <a href="<c:url value='/admin/AdminBookServlet?method=addPre'/>&q

转:Python标准库(非常经典的各种模块介绍)

Python Standard Library 翻译: Python 江湖群 10/06/07 20:10:08 编译 0.1. 关于本书 0.2. 代码约定 0.3. 关于例子 0.4. 如何联系我们 核心模块 1.1. 介绍 1.2. _ _builtin_ _ 模块 1.3. exceptions 模块 1.4. os 模块 1.5. os.path 模块 1.6. stat 模块 1.7. string 模块 1.8. re 模块 1.9. math 模块 1.10. cmath 模块

Some标准模块介绍

IEEE 802.11 无线局域网概述 无线局域网的协议行为建模 IEEE 802.11 无线局域网 MAC 的输入接口 输入接口参数描述如下: Physical Characteristics 物理特征: Rts Threshold (Rts 门限) -- -- X.25模块介绍 OPNET 自带的 X.25 协议模块有:网络层模块( x25_dte_root. x25_dte_chan. x25_dce_root和 x25_dce_chan)和物理层模块( Lapb).基于 X.25 协议的

第三百二十四节,web爬虫,scrapy模块介绍与使用

第三百二十四节,web爬虫,scrapy模块介绍与使用 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫.Scrapy用途广泛,可以用于数据挖掘.监测和自动化测试. Scrapy 使用了 Twisted异步网络库来处理网络通讯.

node.js的request模块

request模块让http请求变的更加简单.最简单的一个示例: 1: var request = require('request'); 2:  3: request('http://www.google.com', function (error, response, body) { 4: if (!error && response.statusCode == 200) { 5: console.log(body); 6: } 7: }) 安装: npm install reques

8.模块介绍 time &amp;datetime模块 random os sys shutil json &amp; picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式

本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.p

Ansible 自动化运维工具之inventory和常用模块介绍

一.inventory介绍 前面我们介绍过ansible的hosts文件是存放被管理主机的,被管理主机比较少的情况下,直接在hosts中定义即可,但是以后很定会管理多台主机,而ansible可管理的主机集合就叫做inventory.在ansible中,描述你主机的默认方法是将它们列在一个文本文件中,这个文件叫inventory文件. 一个简单的inventory文件可能只包含一组主机名的列表,如下: ftp.testansible.com samba.testansible.com mail.t

dojo/request模块整体架构解析

总体说明 做前端当然少不了ajax的使用,使用dojo的童鞋都知道dojo是基于模块化管理的前端框架,其中对ajax的处理位于dojo/request模块.一般情况下我们使用ajax请求只需要引入dojo/request模块,然后按照文档的说明制定参数即可.实际上dojo在这一模块的处理中抽象了很多概念: 平台侦探器:dojo/request/default 请求分发器:dojo/request/registry 全局通知器:dojo/request/notify 数据传输器:dojo/requ

python基础31[常用模块介绍]

python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的libraries(modules)如下: 1)python运行时服务 * copy: copy模块提供了对复合(compound)对象(list,tuple,dict,custom class)进行浅拷贝和深拷贝的功能. * pickle: pickle模块被用来序列化python的对象到bytes流,从