python学习(三)scrapy爬虫框架(四)——数据库的使用

开始前的准备工作:

MySQL下载:点我
python MySQL驱动下载:pymysql(pyMySql,直接用pip方式安装)


全部安装好之后,我们来熟悉一下pymysql模块

import pymysql

#创建链接对象
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='1234', db='python')
#创建游标 游标用来进行查询,修改等操作
cursor = connection.cursor()

#定义sql语句 这里的sql语法根据使用的数据库不同会有一些小差别
sql = "SELECT * FROM python.text_info where text_title='test'"

#执行sql语句 返回受到影响的行数
cursor.execute(sql)

#获取sql语句执行后的返回数据 默认返回的数据类型为元组
#获取所有返回
r = cursor.fetchall()
#获取一个返回
r = cursor.fetchone()
#获取至多三个返回 不足三个时返回所有
r = cursor.fetchmany(3)
#其他的fetch方法可自行百度

#将返回数据类型改为字典
cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
#或者在创建连接对象时指定返回数据类型为字典 建议把返回类型修改为字典类型
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='1234', db='python', cursorclass=pymysql.cursors.DictCursor)

#保存所做的修改 在连接关闭之前,如果你没有调用下面的语句
#那么,你之前的所有修改将不会被保存
connection.commit()

#关闭游标
cursor.close()
#关闭连接
connection.close()

第一步:确定items

我们要爬取的网站是:http://m.50zw.la
要爬取的是小说的信息,如图:
示例1


所以items.py文件如下:

import scrapy


class TextInfoItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    text_name = scrapy.Field()
    text_author = scrapy.Field()
    text_type = scrapy.Field()
    text_status = scrapy.Field()
    text_latest = scrapy.Field()
    text_intro = scrapy.Field()

最后信息是要储存到数据库里的,所以我们还得创建一个数据库表。

  • 第一步:在开始菜单里找到MySQL Workbench,双击打开。MySQL Workbench是MySQL自带的一个可视化管理工具
  • 第二步:连接数据库,创建一个数据库python,再在刚刚创建的数据库里创建一个表text_info
  • 第三步:在text_info表里逐一添加text_name,text_author 等属性,类型全部设置为varchar,大小除了text_intro是1000外,其他的全部设置为50

MySQL的使用与本文无关,就不详细讲了。如果遇到问题,可以评论留言。

第二步:spiders.py

为了简单,我们只爬取50zw网站下的玄幻分类的小说信息。
细节前面已经讲过了,这里不再多讲,有不懂的可以去看前面的几篇博客或者评论留言。废话不多说,直接上代码:

import scrapy
from text_info.items import TextInfoItem

class A50zwSpider(scrapy.Spider):
    name = '50zw'
    allowed_domains = ['m.50zw.la']
    start_urls = ['http://m.50zw.la/wapsort/1_1.html']

    #主站链接 用来拼接
    base_site = 'http://m.50zw.la'

    def parse(self, response):
        book_urls = response.xpath('//table[@class="list-item"]//a/@href').extract()

        for book_url in book_urls:
            url = self.base_site + book_url
            yield scrapy.Request(url, callback=self.getInfo)

        #获取下一页
        next_page_url = self.base_site + response.xpath('//table[@class="page-book"]//a[contains(text(),"下一页")]/@href').extract()[0]
        yield scrapy.Request(next_page_url, callback=self.parse)

    def getInfo(self, response):
        item = TextInfoItem()

        #提取信息
        item['text_id'] = response.url.split('_')[1].replace('/', '')
        item['text_name'] = response.xpath('//table[1]//p/strong/text()').extract()[0]
        item['text_author'] = response.xpath('//table[1]//p/a/text()').extract()[0]
        item['text_type'] = response.xpath('//table[1]//p/a/text()').extract()[1]
        item['text_status'] = response.xpath('//table[1]//p/text()').extract()[2][3:]
        item['text_latest'] = response.xpath('//table[1]//p[5]/text()').extract()[0][3:]
        item['text_intro'] = response.xpath('//div[@class="intro"]/text()').extract()[0]

        yield item

第三步:pipelines.py将信息插入数据库

python对数据库的操作很简单,我们简单了解一下步骤:

  1. 建立数据库连接
  2. 创建操作游标
  3. 写sql语句
  4. 执行sql语句
  5. 如果执行的是查询语句,则用fetch语句获取查询结果
  6. 如果执行的是插入、删除等对数据库造成了影响的sql语句,还需要执行commit保存修改

贴上代码:

import pymysql

class TextInfoPipeline(object):
    def __init__(self):
        #建立数据库连接
        self.connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='1234', db='python',charset='utf8')
        #创建操作游标
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        #定义sql语句
        sql = "INSERT INTO `python`.`text_info` (`text_id`, `text_name`, `text_author`, `text_type`, `text_status`, `text_latest`, `text_intro`) VALUES ('"+item['text_id']+"', '"+item['text_name']+"', '"+item['text_author']+"', '"+item['text_type']+"', '"+item['text_status']+"', '"+item['text_latest']+"', '"+item['text_intro']+"');"

        #执行sql语句
        self.cursor.execute(sql)
        #保存修改
        self.connection.commit()

        return item

    def __del__(self):
        #关闭操作游标
        self.cursor.close()
        #关闭数据库连接
        self.connection.close()

写在最后:

  1. 代码敲好后不要忘记在settings里开启pipelines
  2. pymsql连接时默认的编码是latin-1,所以在建立数据库连接时会增加参数charset来修改编码,要修改为utf-8的话得用charset=’utf8‘,而不是charset=’utf-8‘
  3. 这个网站有些问题,会时不时报404错误,所以在爬的过程中会报list index out of range,这是因为得到了错误得网页,xpath找不到对应得路径返回了空列表。这是正常现象,并不是代码出问题了(当然,如果频繁报错最好是检查一下代码)

贴一张成功后的图片:
示例2


上一篇: python学习(三)scrapy爬虫框架(三)——爬取壁纸保存并命名

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值