python之scrapy初探

1、知识点

"""
Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,我们只需要实现少量的代码,就能够快速的抓取
Scrapy模块:
        1、scheduler:用来存放url队列
        2、downloader:发送请求
        3、spiders:提取数据和url
        4、itemPipeline:数据保存

入门:
    1、创建一个scrapy项目
        scrapy startproject mySpider
    2、生成一个爬虫 ,#定义范围,防止爬去其他网址
        scrapy genspider sina "sina.com.cn"
    3、提取数据
        完善spider,使用xpath等方法
    4、保存数据
        pipeline中保存数据
   5、运行爬虫
     scrapy crawl sina
项目详解: 1、scrapy.cfg:项目配置文件 2、items.py :需要爬去的字段 3、middlewares.py:中间件 4、pipelines.py:数据的处理和保存 , item为爬去的数据
"""

2、目录结构

3、解析案例

# -*- coding: utf-8 -*-
import scrapy


class SinaSpider(scrapy.Spider):
    name = 'sina' #爬虫名
    allowed_domains = ['sina.com.cn']  #允许爬取的范围
    start_urls = ['http://sports.sina.com.cn/nba/']    #开始爬取的url

    def parse(self, response):
        # ret = response.xpath("//div[@class='-live-page-widget']//a/text()").extract()
        # print(ret)
        # pass

        li_list = response.xpath("//div[@class='-live-page-widget']")

        for li in list:
            item = { }
            item["data"]= li.xpath(".//a/text()").extract()[0]
            print(item)
原文地址:https://www.cnblogs.com/ywjfx/p/11070925.html