scrapy爬虫完整的代码实例[通俗易懂]

scrapy爬虫完整的代码实例[通俗易懂]新建工程scrapystartprojecttutorial进入tutorial目录,在spider下面新建quotes_spider.pyimportscrapyfrom..itemsimportQuotesItem#coding:utf-8classQuotesSpider(scrapy.Spider):name=”quot…

大家好,又见面了,我是你们的朋友全栈君。

    新建工程

scrapy startproject tutorial

    进入tutorial目录,在spider下面新建quotes_spider.py

import scrapy
from ..items import QuotesItem

#coding:utf-8

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    allowed_domain = "toscrape.com"

    def start_requests(self):
        for i in range(1,2):
            url = "http://quotes.toscrape.com/page/" + str(i) + "/"
            yield scrapy.Request(url=url,callback=self.parse)


    def parse(self, response):
        item = QuotesItem()
        for quote in response.css('div.quote'):
            item['text'] = quote.css('span.text::text').get(),
            item['author'] = quote.css('small.author::text').get(),
            item['tags'] = quote.css('div.tags a.tag::text').getall()
            yield item

  进入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 TutorialItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

class QuotesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    text = scrapy.Field()
    author = scrapy.Field()
    tags = scrapy.Field()
    pass

    进入pipelines.py进行设置,对数据进行清洗

# -*- 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


class TutorialPipeline(object):
    def process_item(self, item, spider):
        return item

class QuotesPipeline(object):
    def process_item(self,item, spider):
        if item['text']:
            item['text'] = item['text'][0][1:-1]
        if item['author']:
            item['author'] = item['author'][0][1:-1]
        return item

    进入setting.py,修改相关配置

ITEM_PIPELINES = {
   'tutorial.pipelines.TutorialPipeline': 300,
   'tutorial.pipelines.QuotesPipeline': 500,
}
FEED_EXPORT_ENCODING = 'utf-8'

    进行命令行,执行爬虫

scrapy crawl quotes -o quotes.jl
import json
import codecs

class JsonPipeline(object):
    def __init__(self):
        self.file = codecs.open('logs.json', 'w', encoding='utf-8')
    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item
    def spider_closed(self, spider):
        self.file.close()

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/153159.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • SQL注入原理及PreparedStatement的使用

    SQL注入原理及PreparedStatement的使用

    2021年8月8日
    61
  • substring截取字符串特定位置的值

    substring截取字符串特定位置的值1、截取指定字符上的字符串:substring(start,end)start:开始的位置(从0开始索引)包括该位置的字符,不可省略end:结束的位置(不包括该位置上的字符),可省略例:Stringstr=“第1周”;str=str.substring(1,2);str此时里面就剩一个1了若start与end相等,那么返回的就是一个空串若start比end大…

    2022年5月23日
    51
  • php 容器_php依赖注入容器库

    php 容器_php依赖注入容器库原标题:PHP容器——Pimple运行流程浅析需要具备的知识点闭包闭包和匿名函数在PHP5.3.0中引入的。闭包是指:创建时封装周围状态的函数。即使闭包所处的环境不存在了,闭包中封装的状态依然存在。理论上,闭包和匿名函数是不同的概念。但是PHP将其视作相同概念。实际上,闭包和匿名函数是伪装成函数的对象。他们是Closure类的实例。闭包和字符串、整数一样,是一等值类型。创建闭包:$closure…

    2025年8月4日
    3
  • java语法正则表达式_详解Java正则表达式语法

    java语法正则表达式_详解Java正则表达式语法导读热词分享的Java正则表达式语法和示例如下1、匹配验证-验证Email是否正确publicstaticvoidmain(String[]args){//要验证的字符串Stringstr=”service@xsoftlab.net”;//邮箱验证规则StringregEx=”[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){…

    2022年7月19日
    16
  • linux 网口_网络管理员网址

    linux 网口_网络管理员网址Linux12:网络管理文章目录一.网络接口名称规则1.认识网卡2.修改网卡配置文件3.主机名4.网络测试工具一.网络接口名称规则计算机与外界通信的前提是:有网卡(网络适配器NAT)注意:虚拟机的总内存,不能超过真机服务器和客户机:谁提供服务,谁就是服务器1.认识网卡#ls /etc/sysconfig/network-scripts/补充:网络管理器NetworkManager,动态网络的控制器与配置系统,它用于当网络设备可用时保持设备和连接开启并激活查看该服务的运行状况:#

    2022年8月9日
    7
  • windows打开多个微信_win7怎么运行两个相同软件

    windows打开多个微信_win7怎么运行两个相同软件windows 打开多个微信

    2022年4月21日
    112

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号