Python爬虫——8-1.scrapy深度爬取案例—百思不得姐

对于scrapy框架的使用,爬取数据,多次运行命令行也是比较头疼和麻烦的,这里建议Windows+R键输入cmd进入命令行,切入至项目所在目录后执行scrapy shell  url’命令,可以很直观的检测程序是否出错,如xpath匹配路径是否正确获取数据,这是一个用于简单测试的非常便捷的方法。



1.创建项目:scrapy startprojet budejie


2.定义数据模型文件——items.py文件:

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class BudejieItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    content=scrapy.Field()
3.爬虫程序文件——budejie.py文件
 
# coding:utf-8
'''
使用scrapy框架进行深度爬虫,爬取百思不得姐的内涵段子
'''
# 引入需要的模块
import scrapy
from ..items import BudejieItem
class BudejieSpider(scrapy.Spider):
    name='baisibudejie'
    allowed_domains=['budejie.com']
    start_urls=['http://www.budejie.com/text/2']

    def parse(self,response):
        '''
        在这个函数中不做任何数据处理,只是将第一个url加入到urljoin        并将请求对象交给parse_response进行数据处理
        :param response:
        :return:
        '''
        url=response.urljoin(self.start_urls[0])
        yield scrapy.Request(url,callback=self.parse_response)

    def parse_response(self,response):
        '''
        在这个函数中才是真的数据处理,将筛选后的数据逐个交给pipelines管道模块进行存储
        :param response:
        :return:
        '''
        # 1.将数据保存在本地表格文件,一般用于测试
        # 定义一个列表,专门用于保存段子内容
        content_list=[]
        # 使用xpath对段子内容进行过滤、筛选
        contents= response.xpath("//div[@class='j-r-list-c']/div[@class='j-r-list-c-desc']/a").xpath("string(.)").extract()
        for content in contents:
            new_item=BudejieItem()
            new_item['content']=content
            content_list.append(new_item)
            yield new_item


        # 将第一页的数据爬取筛选完毕后,筛选页面链接/a/@href,.extract()是将选择器对象转换成Unicode对象
        page_list=response.xpath("//div[@class='m-page m-page-sr m-page-sm']/a/@href").extract()

        for page in page_list:
            # 将路由交由urljoin()管理,去重
            url=response.urljoin(page)
            # 创建新的请求对象,交由自己处理,递归,依次筛选数据,并yield交给管道模块
            yield scrapy.Request(url,callback=self.parse_response)
4.管道模块:pipelines.py文件,记得在settngs.py文件中将对应的pipeline类型添加
ITEM_PIPELINES = {
   'budejie.pipelines.BudejiePipeline': 300,
}
 
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import pymysql
pymysql.install_as_MySQLdb()
class BudejiePipeline(object):
    def __init__(self):
        '''
        初始化函数,与数据库建立连接
        '''
        self.engine=create_engine('mysql://root:0@localhost/python_spider?charset=utf8')
        Session=sessionmaker(bind=self.engine)
        self.session=Session()

    def close_spider(self,spider):
        '''
        在爬虫程序关闭调用的函数,关闭数据库的连接

        :param spider:
        :return:

        '''
        # 在关闭与数据库连接之前确保所有的sql语句已经提交
        self.session.commit()
        self.session.close()
    def process_item(self, item, spider):
        '''
        核心处理函数,专门处理爬虫程序中已经封装好的item对象
        :param item:
        :param spider:
        :return:
        '''
        print('正在保存数据')
        sql="insert into budejie(content) values('%s')"%item['content']
        # 执行sql语句
        self.session.execute(sql)

 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值