python爬虫入门————————————————第一节

版权声明:CSDN 博主刘康康 https://blog.csdn.net/liiukangkang/article/details/84496294

1.爬虫入门概述

爬虫,又被称为网络爬虫,主要指代从互联网上进行数据采集的脚本后者程序,是进行数据 分析和数据挖掘的基础。 

所谓爬虫就是指在给定url(网址)中获取我们对我们有用的数据信息,通过代码实现数据的大量获取,在经过后期的数据整理、计算等得出相关规律,以及行业趋势等信息。

通常我们说的爬虫

2.爬虫分类

  • 按照使用情况,主要分为两大类型:通用爬虫聚焦爬虫
  • 按照采集数据的过程进行区分又可分为 积累爬虫增量爬虫

2.1通用爬虫&聚焦爬虫

通用爬虫:最常见的数据采集程序,是网络上搜索引擎使用的脚本程序,搜索引擎通过通用爬虫进行互联网上的数据搜集,提供给自己的客户进行数据搜索使用;(缺点)通用爬虫采集的数据具有普遍性、针对性较差(优点)但是通用爬虫的重用性较高,一旦开发调试完成、可以长时间运行给搜索引擎提供需要的数据。

聚焦爬虫:是数据供应商企业使用最多的爬虫程序,优点:通常情况针对指定范围的数据进行定向的数据采集和筛选能在一定时间段内最大限度的采集企业需要的有效的数据;缺点:但是重用性较差,一般针对不同的数据需求,需要独立开发爬虫程序进行数据采集。 

2.2 积累爬虫&增量爬虫

积累爬虫:目标数据一旦生成,不会发生改动,随着时间的延伸数据量逐渐增大,累积爬虫就是采集这样的数据,采集并保存历史数据,之后针对新生成的数据进一步获取,采集过程中不会更新历史数据;如采集期权股票的数据、房地产地域价格历史数据等等. 

增量爬虫:目标数据在需求更改过程中,可能会随时发生变化;历史数据的变动和新增数据都被称为增量,所以针对此类数据采集的爬虫程序,称为增量爬虫;增量爬虫的特点就是在采集数据的过程中随时更新历史数据的同时采集新增数据。如搜索引擎采集网络数据,网络上的网页数据随时可能发生变化,需要爬虫针对采集的历史数据随时进行更新并采集新增的网页数据。 

3.爬虫之优

为什么要使用爬虫?

爬虫的作用是从网站上采集(下载)数据的,目前市面上流行的下载工具比比皆是,使用爬虫的优势和使用场景的目的性一定要明确; 
所以如果要下载一部电影?保存一张图片?存储一片论文?下载一本小说?下载一个网站 上所有网页数据?不同的使用场景下到底怎样操作才是最有效率的做法,工欲善其事,在利其器之前我们首先要明确所善何事何时何地。 
爬虫的优势是将下载数据的过程通过编写的程序实现自动化批量处理,但是自动化有两个前提条件

  • 需要编写程序、
  • 可以批量处理、

这两个前提条件同样也说明了爬虫的使用场景

⚫ 采集数据之前,对目标数据进行分析,并编写程序代码 

⚫ 目标数据是批量数据(非单个/极少量数据),批量数据有自己的组成规律 

3.1爬虫使用注意事项

爬虫技术在一定程度上还是备受争议的,尤其是聚焦爬虫在数据处理过程中对于目标数据所在的服务器会造成短时间的压力提升;爬虫程序由于程序本身的特殊性,在一定程度上可能会引发一些对网站的恶意攻击行为;爬虫采集数据的过程中对于数据的涉密性区分不是很严格,主要靠人工手段进行筛选操作;所以爬虫处理过程中一定要注意如下问题:

  • 爬虫采集的目标数据量进行分析
  • 爬虫采集的目标数据涉密性进行分析
  • 爬虫采集目标数据的频率进行分析 

4.爬虫入门程序

4.1爬虫采集数据,主要采集网站数据,通 常情况下操作步骤如下:

⚫ 确定目标网站url地址

⚫ 对目标 url 地址发送请求

⚫ 获取网站返回的响应数据

⚫ 对响应数据进行解析处理

⚫ 得到目标数据 

4.2入门操作————自己尝试一下吧

给定url        http://finance.eastmoney.com/news/cgsxw_1.html

python3.6下的爬虫程序  (ps:记得导入相应的模块)

"""
Version 1.1.0
Author lkk
Email [email protected]
date 2018-11-19 14:10
DESC 获取新闻网站的新闻
"""
from urllib import request
import re
from fake_useragent import UserAgent
import chardet
import pymysql


def parse():
    ua = UserAgent()
    headers = {'User-agent': ua.random}  # 创建代理对象以及请求头
    url = 'http://finance.eastmoney.com/news/cgsxw_1.html'  # 初始url
    base = 'http://finance.eastmoney.com/news/'  # 基础url 获取下一页时3使用
    start = request.Request(url, headers=headers)
    response = request.urlopen(start)
    content = response.read()
    encoding = chardet.detect(content).get('encoding')
    content = content.decode(encoding, 'ignore')
    news = re.findall(r'<div[^>]+class="text\s+text-no-img">\s+(.*?)</div>', content, re.S)  # 使用正则匹配我么所需的数据
    for jokes in news:
        link = re.findall(r'<a\s+href="(.*?)"\s+target="_blank">', jokes)
        title = re.findall(r'<a.*?>\s+(.*?)\s+</a>', jokes)
        info = re.findall(r'<p[^>]+class="info".*?>\s+(.*?)\s+</p>', jokes)
        times = re.findall(r'<p[^>]+class="time".*?>\s+(.*?)\s+</p>', jokes)
        print(link, title, info, times)
    next_page = re.findall(r'<a\s+href="(.*?)"\s+target="_self".*?>下一页</a>', content)
    print(next_page)
    while True:
        next_page = re.findall(r'25</a>\s*<a\s+href="(.*?)"\s+target="_self".*?>下一页</a>', content)
        print(next_page)
        if len(next_page) <= 0:
            print("数据采集完毕")
            break
        # 采集下一页
        next_content = request.Request(base + next_page[0], headers=headers)
        response = request.urlopen(next_content)
        content = response.read()
        encoding = chardet.detect(content).get('encoding')
        content = content.decode(encoding, 'ignore')
        news = re.findall(r'<div[^>]+class="text\s+text-no-img">\s+(.*?)</div>', content, re.S)
        for jokes in news:
            link = re.findall(r'<a\s+href="(.*?)"\s+target="_blank">', jokes)
            title = re.findall(r'<a.*?>\s+(.*?)\s+</a>', jokes)[0]
            info = re.findall(r'<p[^>]+class="info".*?>\s+(.*?)\s+</p>', jokes)[0]
            times = re.findall(r'<p[^>]+class="time".*?>\s+(.*?)\s+</p>', jokes)[0]
            print(link[0], title, info, times)
            mysql(link, title, info, times)


class DownMysql:
    """数据持久化存储"""
    def __init__(self, link, title, info, times):
        self.link = link
        self.title = title
        self.info = info
        self.times = times
        self.connect = pymysql.connect(
            host='localhost',
            db='data',  # 数据库名
            port=3306,
            user='root',
            passwd='123456',  # 数据库密码
            charset='utf8',
            use_unicode=False
        )
        self.cursor = self.connect.cursor()

    # 保存数据到MySQL中
    def save_mysql(self):
        sql = "insert into task1(link,title,info,times) VALUES (%s,%s,%s,%s)"
        try:
            self.cursor.execute(sql, (self.link, self.title, self.info, self.times))
            self.connect.commit()
            print('数据插入成功')
        except Exception as e:
            print(e, '数据插入错误')


# 新建对象,然后将数据传入类中
def mysql(link, title, info, times):
    down = DownMysql(link, title, info, times)
    down.save_mysql()


if __name__ == '__main__':
    parse()

4.3数据编码处理
 我们通过爬虫程序可以得到网站返回的数据,但是返回的数据在展示过程中,出现了乱码的问题,是因为网站本身有自己的字符编码(通常情况下是UTF-8),我 们程序在采集完成之后在控制台进行展示的过程中是 使用本地默认编码(windows 一般是 gbk、 unix中一 般是utf-8),如果两部分编码不一致,就会出现乱码的问题。 
 

猜你喜欢

转载自blog.csdn.net/liiukangkang/article/details/84496294