爬虫01:概述,环境,模块

爬虫•目录 爬虫•类别


获取数据的方式

  • 自有数据
  • 第三方购买
    数据堂
    贵阳大数据交易所
  • 爬虫爬取数据
    市场上没有,价格太高,利用爬虫程序爬取

python

请求模块,解析模块丰富成熟,scrapy框架

python的多线程由于全局解释器锁的存在,只有对于I/O密集型的相对效果好一点.
C/C++ 效率高,但是上手并不那么容易.

爬虫分类

  • 通用网络爬虫(搜索引擎,遵守robots协议
    ex:https://www.baidu.com/robots.txt
  • 聚焦网络爬虫
    自己写的爬虫程序,面向需求爬虫

    爬虫程序会对对方服务器造成压力(高并发),反反爬

爬取数据的步骤

  • step1.确定爬取的URL地址
  • step2.通过HTTP/HTTPS协议获取相应的页面
  • step3.提取相应中有用的数据
    1)所需数据,保存
    2)页面中有其他的URL,继续step2

集成python开发环境

Anaconda

安装搜索引擎找一下 它是一个集成的工具 不需要复杂的配置python的环境和包

Anaconda环境安装模块

  • (管理员方式)进入到Anaconda Prompt
  • 执行安装命令
    conda install pymongo
    conda install pymysql

Spyder

anaconda内包含编辑器

  • 快捷键
    注释 ctrl+1
    运行 F5

    tools>preference 查看

Chrome浏览器插件

  • Proxy SwitchyOmega
  • XPathHelper
  • JSONView

他不是必须的

WEB

  • HTTP/HTTPS
    HTTP: 80
    HTTPS: 443,HTTP加了安全套节层
  • GET POST
    GET: 查询参数在URL地址上显示出来
    POST: 查询参数和需要提交的数据隐藏在Form表单中,不会在URL地址上都显示.
  • URL
    统一资源定位符
    ex:https://item.jd.com/37289659363.html#detail
    协议    域名/IP   访问资源路径  锚点   

    nslookup www.baidu.com 获取ip地址

  • User-Agent
    记录用户浏览器,操作系统,为了让用户获取更好的页面效果...(爬虫伪装User-Agent,多伪装一些,模拟多个浏览器请求)

爬虫请求模块

1.模块

  • python2: urllib urllib2
  • python3: urllib.request(合并)

2.常用方法

  • urllib.request.urlopen(’URL地址’)
    1.作用: 向网站发起请求并获取响应对象
    2.不支持重构User-Agent

    
      import urllib.request
    
      #向网站发起请求获取响应对象
      url = 'http://www.baidu.com/'
      res = urllib.request.urlopen(url)
    
      #获取响应对象的内容
      print(res.read().decode('utf-8'))
    
      #encode():字符串转为bytes decode():bytes转为string
    
  • urllib.request.Request(’url’,headers={})
    1.使用流程

    • step1 创建请求对象(Request())
    • step2 发请求获取响应(Urlopen())
    • step3 获取相应内容(read().decode(‘utf-8’))

      #定义变量
      url = 'http://www.baidu.com/'
      headers = {Mozilla/5.0 (Windows NT 6.1; WOW64) 
      AppleWebKit/537.36 (KHTML, like Gecko) 
      Chrome/39.0.2171.71 Safari/537.36}
      
      #step1:创建请求对象
      req = urllib.request.Request(url,headers=headers)
      
      #step2:获取响应对象
      res = urllib.request.urlopen(req)
      
      #step1:获取响应内容
      html = req.read().decode('utf-8')
      print(html)
      
  • 响应对象(res)的方法
    • 1.read()
    • 2.getcode() 返回HTTP的响应码
      200:成功
      4XX:服务器页面出错
      5XX:服务器出错
    • 3.geturl()  返回实际数据的url地址

URL编码模块 urlllib.parse

  • 1.urlencode({字典})

    • ex:key = {'wd':'经济'};urllib.parse.urlencode(key)
      Out[01]: ‘wd=%E7%BB%8F%E6%B5%8E’ 返回值为字符串

      通过对查询参数进行编码,和资源路径拼接成字符串

    • EX:终端输入内容,得到百度搜索结果,保存本地

        import urllib.request
        import urllib.parse
      
        # 1定义常用变量
        baseurl = 'http://www.baidu.com/s?'
        headers = {'User-Agent':''}
        key = input('>>>')
      
        ## 编码URL,拼接URL
        key = urllib.parse.urlencode({'wd':key})
        url = baseurl + key
      
        # 2拼接URL发请求响应
        req = urllib.request.Request(url, headers=headers)
        res = urllib.request.urlopen(req)
        html = res.read().decode('utf-8')
      
        # 3保存到本地
        with open('baidu.html', 'w', encoding='utf-8') as f:
            f.write(html)
      
  • 2.quote(‘字符串’)

    • ex:s = urllib.parse.quote('经济')
    • 更改其中两句命令
        baseurl = 'http://www.baidu.com/s?wd='
        key = urllib.parse.quote(key)
      
  • 3.unquote(‘字符串’)

    • ex:s = urllib.parse.unquote('%E7%BB%8F%E6%B5%8E')

案例

百度贴吧数据抓取

要求:输入贴吧名字,起始页,终止页,响应内容保存本地,一个页面保存一个文件

步骤

import urllib.request
import urllib.parse
import time

class BaiduSpider(object):
    def __init__(self):
        self.baseurl = 'http://tieba.baidu.com/f?'
        self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'}

    def getPage(self, url):
        '''获取页面函数
        '''
        req = urllib.request.Request(url, headers=self.headers)
        res = urllib.request.urlopen(req)
        html = res.read().decode('utf-8')
        return html

    def writePage(self, filename, html):
        '''保存数据函数
        '''
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(html)

    def workOn(self):
        '''主函数
        '''
        # 定义常用变量
        name = input('贴吧名>>>')
        begin = int(input('起始页>>>'))
        end = int(input('终止页>>>'))

        ## 编码URL,拼接URL
        kw = urllib.parse.urlencode({'kw':name})
        ## 编码每一页URL,拼接URL
        for page in range(begin, end+1):
            pn = (page - 1) * 50
            url = self.baseurl + kw + '&pn' + str(pn)
            html = self.getPage(url)
            filename = name + '吧第%s页.html' % page
            self.writePage(filename, html)
            print(filename, '爬取成功')
            time.sleep(0.1)


if __name__ == '__main__':
    spdier = BaiduSpider()
    spdier.workOn()

博主个人能力有限,错误在所难免.
如发现错误请不要吝啬,发邮件给博主更正内容,在此提前鸣谢.
Email: JentChang@163.com (来信请注明文章标题,如果附带链接就更方便了)
你也可以在下方的留言板留下你宝贵的意见.


上一篇
爬虫02:请求及案例 爬虫02:请求及案例
爬虫•目录 爬虫•类别 1.GET1特点值在url后面 以键值的形式追加在后面  2案例上节案例 2.POST(在Request()中添加data参数)data参数urllib.request.Request(url, data=data
2019-01-22
下一篇
统计学39:抽样分布例题 统计学39:抽样分布例题
统计学•目录 统计学•类别 math 抽样分布例题The averagemale drinks 2L of water when active outdoors(with a standard deviation of 0.7L). Y
2019-01-01
目录