爬虫基础项目从入门到实战

156 阅读9分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

前言


一、爬虫的基本流程

本文章代码均来源于b站视频:https://www.bilibili.com/video/BV12E411A7ZQ?p=16&spm_id_from=pageDriver.

1-1、准备工作

通过浏览器点击F12查看分析目标网页,查看网页源码。

1-2、获取数据

发起访问请求,请求包含额外的header等信息,如果服务器正常相应,则得到一个Response,及所要获得的页面内容。

1-3、解析内容

得到的内容一般是HTML格式,我们使用页面解析库、正则表达式等进行解析。

1-4、保存数据

保存形式多种多样,保存数据为常见的Excel、csv等,或者直接保存到数据库,或者保存成特定格式的文件。

二、项目实战

2-1、导入相关工具包

# -*- codeing = utf-8 -*-
# coding=utf-8
# 以上任意一种都可以,编码规范,这样可以在代码中包含中文。

from bs4 import BeautifulSoup  # 网页解析,获取数据
import re  # 正则表达式,进行文字匹配`
import urllib.request, urllib.error  # 制定URL,获取网页数据
import xlwt  # 进行excel操作
# 如果数据量小,则不需要使用到数据库,只用xlwt进行excel操作即可
#import sqlite3  # 进行SQLite数据库操作

2-2、正则表达式基础

有关正则表达式的详细使用请查看我的另一篇文章(正则表达式——re库的一些常用函数).

# 以下正则表达式为项目中所需要使用到的。

# 用正则表达式来匹配链接、图片、title等。
findLink = re.compile(r'<a href="(.*?)">')  # 创建正则表达式对象,标售规则   影片详情链接的规则
# re.S:让换行符包含在字符中。
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人评价</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
# ?: 出现0次或者1次,把大于一次的条件筛选掉。
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)

2-3、主函数

def main():
    baseurl = "https://movie.douban.com/top250?start="  #要爬取的网页链接
    # 1.爬取网页
    datalist = getData(baseurl) #[[doc1],[doc2]...]
    # [    "url..", "str", 'txt" '\d']
    savepath = "豆瓣电影Top250.xls"    #当前目录新建XLS,存储进去
    # dbpath = "movie.db"              #当前目录新建数据库,存储进去
    # 3.保存数据
    saveData(datalist,savepath)      #2种存储方式可以只选择一种
    # saveData2DB(datalist,dbpath)

2-4、getData函数

有关BeautifulSoup的详细使用请查看我的另一篇文章(Beautiful Soup介绍).

def getData(baseurl):
    datalist = []  #用来存储爬取的网页信息
    for i in range(0, 10):  # 调用获取页面信息的函数,10次
        url = baseurl + str(i * 25)
        # askURL函数的含义是得到指定的网页内容,详细内容在2-5
        html = askURL(url)  # 保存获取到的网页源码

        # 2.逐一解析数据
        # BeautifulSoup: 可以将复杂的HTML文档转换为一个树形结构。
        # 实例化对象可以直接调用标签,返回相应标签,默认只返回找到的第一个标签
        # 如 bs.title,bs.a,bs.div等等。使用bs.title.string可以直接拿到对应的内容。
        # 如果对应的内容是注释形式,<!--新闻-->,则会默认去掉注释,返回对应内容 。
        # 使用bs.a.attrs可以获得所有属性。
        #
        # "html.parser": 解析器,表明解析的是html,BeautifulSoup还可以解析许多其他格式的文件。
        soup = BeautifulSoup(html, "html.parser")
        # find_all: 找到所有的标签,参数可以是标签内含有的各种属性,比如说id、class_、herf等。
        # limit参数:限定获取到多少个数据。
        for item in soup.find_all('div', class_="item"):  # 查找符合要求的字符串
            data = []  # 保存一部电影所有信息
            # 转换成字符串,用正则表达式来查找符合要求的字符串
            item = str(item)
            # 找到相应的链接。并将其加入到data列表中。
            link = re.findall(findLink, item)[0]  # 通过正则表达式查找
            data.append(link)
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)

            titles = re.findall(findTitle, item)
            # 如果中文英文名都有
            if (len(titles) == 2):
                # 添加中文名
                ctitle = titles[0]
                data.append(ctitle)
                # 添加英文名
                otitle = titles[1].replace("/", "")  #消除转义字符
                data.append(otitle)
            else:
                data.append(titles[0])
                # 英文名留空
                data.append(' ')
            rating = re.findall(findRating, item)[0]
            data.append(rating)
            judgeNum = re.findall(findJudge, item)[0]
            data.append(judgeNum)
            # 添加概述
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")
                data.append(inq)
            else:
                # 如果为空,就添加一个空值。
                data.append(" ")
            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)
            bd = re.sub('/', "", bd)
            data.append(bd.strip())
            datalist.append(data)

    return datalist

    # 其他
    # 通过子标签来查找
    # 找到head里包含title的标签
    # bs.select("head > title")

# 得到指定一个URL的网页内容

2-5、askURL函数

# 得到指定一个URL的网页内容
def askURL(url):
    head = {  # 模拟浏览器头部信息,向豆瓣服务器发送消息
        "User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122  Safari / 537.36"
    }
    # 用户代理,表示告诉豆瓣服务器,我们是什么类型的机器、浏览器(本质上是告诉浏览器,我们可以接收什么水平的文件内容)

    # 封装请求信息,伪装成正常请求,防止被识别为爬虫
    # 参数:data:请求的数据
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        #
        response = urllib.request.urlopen(request)
        # decode("utf-8"): 解码为utf-8.把读取的二进制文件进行转换。
        # 有些网页可能并不需要解码。
        html = response.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html


2-6、saveData函数

有关使用Python向Excel中写入数据的详细使用请查看我的另一篇文章(python向Excell中写入数据). 注意:当前直接将数据保存于Excel中,如果要保存到轻便型数据库sqlite3中,则只需要将下边的注释打开即可。 有关轻便型数据库sqlite3的详细使用请查看我的另一篇文章(python库之—psycopg2)(使用方法类似).

# 保存数据到表格
def saveData(datalist,savepath):
    print("save.......")
    #
    book = xlwt.Workbook(encoding="utf-8",style_compression =0) #创建workbook对象
    sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) #创建工作表
    col = ("电影详情链接","图片链接","影片中文名","影片外国名","评分","评价数","概况","相关信息")
    for i in range(0,8):
        sheet.write(0,i,col[i])  #列名
    for i in range(0,250):
        # print("第%d条" %(i+1))       #输出语句,用来测试
        data = datalist[i]
        for j in range(0,8):
            sheet.write(i+1,j,data[j])  #数据
    book.save(savepath) #保存

# def saveData2DB(datalist,dbpath):
#     init_db(dbpath)
#     conn = sqlite3.connect(dbpath)
#     cur = conn.cursor()
#     for data in datalist:
#             for index in range(len(data)):
#                 if index == 4 or index == 5:
#                     continue
#                 data[index] = '"'+data[index]+'"'
#             sql = '''
#                     insert into movie250(
#                     info_link,pic_link,cname,ename,score,rated,instroduction,info)
#                     values (%s)'''%",".join(data)
#             # print(sql)     #输出查询语句,用来测试
#             cur.execute(sql)
#             conn.commit()
#     cur.close
#     conn.close()


# def init_db(dbpath):
#     sql = '''
#         create table movie250(
#         id integer  primary  key autoincrement,
#         info_link text,
#         pic_link text,
#         cname varchar,
#         ename varchar ,
#         score numeric,
#         rated numeric,
#         instroduction text,
#         info text
#         )
#
#
#     '''  #创建数据表
#     conn = sqlite3.connect(dbpath)
#     cursor = conn.cursor()
#     cursor.execute(sql)
#     conn.commit()
#     conn.close()

2-7、全部代码

# -*- codeing = utf-8 -*-
# coding=utf-8
# 以上任意一种都可以,编码规范,这样可以在代码中包含中文。

from bs4 import BeautifulSoup  # 网页解析,获取数据
import re  # 正则表达式,进行文字匹配`
import urllib.request, urllib.error  # 制定URL,获取网页数据
import xlwt  # 进行excel操作
#import sqlite3  # 进行SQLite数据库操作


# 用正则表达式来匹配链接、图片、title等。
findLink = re.compile(r'<a href="(.*?)">')  # 创建正则表达式对象,标售规则   影片详情链接的规则
# re.S:让换行符包含在字符中。
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人评价</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
# ?: 出现0次或者1次,把大于一次的条件筛选掉。
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)



def main():
    baseurl = "https://movie.douban.com/top250?start="  #要爬取的网页链接
    # 1.爬取网页
    datalist = getData(baseurl) #[[doc1],[doc2]...]
    # [    "url..", "str", 'txt" '\d']
    savepath = "豆瓣电影Top250.xls"    #当前目录新建XLS,存储进去
    # dbpath = "movie.db"              #当前目录新建数据库,存储进去
    # 3.保存数据
    saveData(datalist,savepath)      #2种存储方式可以只选择一种
    # saveData2DB(datalist,dbpath)



# 爬取网页
def getData(baseurl):
    datalist = []  #用来存储爬取的网页信息
    for i in range(0, 10):  # 调用获取页面信息的函数,10次
        url = baseurl + str(i * 25)
        #
        html = askURL(url)  # 保存获取到的网页源码

        # 2.逐一解析数据
        # BeautifulSoup: 可以将复杂的HTML文档转换为一个树形结构。
        # 实例化对象可以直接调用标签,返回相应标签,默认只返回找到的第一个标签
        # 如 bs.title,bs.a,bs.div等等。使用bs.title.string可以直接拿到对应的内容。
        # 如果对应的内容是注释形式,<!--新闻-->,则会默认去掉注释,返回对应内容 。
        # 使用bs.a.attrs可以获得所有属性。
        #
        # "html.parser": 解析器,表明解析的是html,BeautifulSoup还可以解析许多其他格式的文件。
        soup = BeautifulSoup(html, "html.parser")
        # find_all: 找到所有的标签,参数可以是标签内含有的各种属性,比如说id、class_、herf等。
        # limit参数:限定获取到多少个数据。
        for item in soup.find_all('div', class_="item"):  # 查找符合要求的字符串
            data = []  # 保存一部电影所有信息
            # 转换成字符串,用正则表达式来查找符合要求的字符串
            item = str(item)
            # 找到相应的链接。并将其加入到data列表中。
            link = re.findall(findLink, item)[0]  # 通过正则表达式查找
            data.append(link)
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)

            titles = re.findall(findTitle, item)
            # 如果中文英文名都有
            if (len(titles) == 2):
                # 添加中文名
                ctitle = titles[0]
                data.append(ctitle)
                # 添加英文名
                otitle = titles[1].replace("/", "")  #消除转义字符
                data.append(otitle)
            else:
                data.append(titles[0])
                # 英文名留空
                data.append(' ')
            rating = re.findall(findRating, item)[0]
            data.append(rating)
            judgeNum = re.findall(findJudge, item)[0]
            data.append(judgeNum)
            # 添加概述
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("", "")
                data.append(inq)
            else:
                # 如果为空,就添加一个空值。
                data.append(" ")
            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)
            bd = re.sub('/', "", bd)
            data.append(bd.strip())
            datalist.append(data)

    return datalist

    # 其他
    # 通过子标签来查找
    # 找到head里包含title的标签
    # bs.select("head > title")

# 得到指定一个URL的网页内容
def askURL(url):
    head = {  # 模拟浏览器头部信息,向豆瓣服务器发送消息
        "User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122  Safari / 537.36"
    }
    # 用户代理,表示告诉豆瓣服务器,我们是什么类型的机器、浏览器(本质上是告诉浏览器,我们可以接收什么水平的文件内容)

    # 封装请求信息,伪装成正常请求,防止被识别为爬虫
    # 参数:data:请求的数据
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        #
        response = urllib.request.urlopen(request)
        # decode("utf-8"): 解码为utf-8.把读取的二进制文件进行转换。
        # 有些网页可能并不需要解码。
        html = response.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html


# 保存数据到表格
def saveData(datalist,savepath):
    print("save.......")
    #
    book = xlwt.Workbook(encoding="utf-8",style_compression =0) #创建workbook对象
    sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) #创建工作表
    col = ("电影详情链接","图片链接","影片中文名","影片外国名","评分","评价数","概况","相关信息")
    for i in range(0,8):
        sheet.write(0,i,col[i])  #列名
    for i in range(0,250):
        # print("第%d条" %(i+1))       #输出语句,用来测试
        data = datalist[i]
        for j in range(0,8):
            sheet.write(i+1,j,data[j])  #数据
    book.save(savepath) #保存

# def saveData2DB(datalist,dbpath):
#     init_db(dbpath)
#     conn = sqlite3.connect(dbpath)
#     cur = conn.cursor()
#     for data in datalist:
#             for index in range(len(data)):
#                 if index == 4 or index == 5:
#                     continue
#                 data[index] = '"'+data[index]+'"'
#             sql = '''
#                     insert into movie250(
#                     info_link,pic_link,cname,ename,score,rated,instroduction,info)
#                     values (%s)'''%",".join(data)
#             # print(sql)     #输出查询语句,用来测试
#             cur.execute(sql)
#             conn.commit()
#     cur.close
#     conn.close()


# def init_db(dbpath):
#     sql = '''
#         create table movie250(
#         id integer  primary  key autoincrement,
#         info_link text,
#         pic_link text,
#         cname varchar,
#         ename varchar ,
#         score numeric,
#         rated numeric,
#         instroduction text,
#         info text
#         )
#
#
#     '''  #创建数据表
#     conn = sqlite3.connect(dbpath)
#     cursor = conn.cursor()
#     cursor.execute(sql)
#     conn.commit()
#     conn.close()

# 程序入口
if __name__ == "__main__":  # 当程序执行时
    # 调用函数
     main()
    # init_db("movietest.db")
     print("爬取完毕!")