首页 > 其他 > 详细

scrapy框架的基础使用流程

时间:2019-04-08 16:28:51      阅读:147      评论:0      收藏:0      [点我收藏+]

前提是安装好各种准备库。

1.新建一个工程

在终端输入:scrapy startprojetc 你的项目名, 和django比较类似

# scrapy.cfg  项目的主配置信息
# items.py 设置数据存储模版,用于结构化数据
# pipelines.py  数据持久化处理
# settings.py 配置文件
# spiders 爬虫的目录

2.在目录下创建一个爬虫文件

   2.1 在终端切换到工程目录,然后输入:scrapy genspider 爬虫文件的名称 起始url

创建好后会自动给你包含如下的代码的文件

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


class FirstfileSpider(scrapy.Spider):
    name = ‘firstfile‘
    allowed_domains = [‘www.xiushibaike.com‘]
    start_urls = [‘http://www.xiushibaike.com/‘]

    def parse(self, response):
        pass

所有的爬虫类都会继承这个Spider类,name是对应爬虫文件的名称(在多个爬虫文件中),allowed_domains是允许的域名,只可以爬取指定域名下的页面数据,也可以指定多个域名。start_urls是起始url,表示当前工程将要爬取的页面url,注意要符合前面的允许的域名。最后的parse函数是对获取的页面数据指定内容的解析。response参数指的的拿到的响应对象。注意parse方法的返回值必须为迭代器或者空。

3.对应的文件中编写爬虫的功能程序

 

4.配置文件的编写

刚开始使用时settings.py文件就注意两个参数,USER_AGENT爬虫身份伪装(就是那个headers中的USER-Agent),ROBOSTXT_OBEY表示是否遵守RobotTxt协议。

5.执行代码

终端中输入命令:scrapy crawl 文件名

简单的示例:爬取嗅事百科段子作者与内容。

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


class FirstfileSpider(scrapy.Spider):
    name = ‘firstfile‘
    # 这个一般不用
    # allowed_domains = [‘www.qiushibaike.com‘]
    start_urls = [‘https://www.qiushibaike.com/text/‘]

    def parse(self, response):

        # 使用框架的xpath接口
        list_div = response.xpath(‘//div[@id="content-left"]/div‘)
        for div in list_div:
            author = div.xpath("./div/a[2]/h2/text()").extract()[0]
            content = div.xpath("./a/div/span/text()").extract()[0]
            print(author)
            print(content)

scrapy框架的基础使用流程

原文:https://www.cnblogs.com/haoqirui/p/10671240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!