python3利用Scrapy实现爬虫--学习笔记

本文介绍使用Python Scrapy框架爬取优快云博客阅读排行榜的方法。通过创建项目、定义爬取项、编写爬虫逻辑及设置数据管道,实现对指定页面上的文章标题与阅读数的抓取,并将数据保存到本地文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:需要从网页上爬去一些信息

工具:Python scrapy


爬去优快云中博客的阅读排行

第一步:

创建scrapy项目  scrapy startproject XXX


第二步:

创建爬虫 进入项目目录 执行 scrapy genspider csdn_spider youkuaiyun.com


此时的项目结构为


第三步:

编辑 csdn/item.py 定义我们需要爬取的字段

这里我们爬取 阅读排行前十名的 文章标题和阅读次数

name 为文章标题

total 为阅读数量

import scrapy


class CsdnItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    total = scrapy.Field()

第四部:

编辑爬虫文件 csdn/spiders/csdn_spider.py

import scrapy
from csdn.items import CsdnItem


class CsdnSpiderSpider(scrapy.Spider):
    name = 'csdn_spider'
    allowed_domains = ['youkuaiyun.com']
    start_urls = ['https://blog.youkuaiyun.com/wuchenlhy']

    def parse(self, response):
        body = response.xpath('//*[@id="hotarticls"]/ul[2]/li')
        for value in body:
            title = value.xpath('./a/@title').extract()[0]
            total = value.xpath('./span/text()').extract()[0]
            print(title, total)
            item = CsdnItem()
            item['name'] = title
            item['total'] = total
            yield item

第五步:

保存我们爬取到的内容

编辑csdn/settings.py

找到这一段代码取消掉注释

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'csdn.pipelines.CsdnPipeline': 300,
#}

变成这个样子

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'csdn.pipelines.CsdnPipeline': 300,
}

之后编辑csdn/pipelines.py

class CsdnPipeline(object):

    def process_item(self, item, spider):
        with open('csdn.txt', 'a') as fp:
            fp.write('{0} {1}\n'.format(item['name'], item['total']))

爬虫代码完毕

最后一步:运行爬虫

scrapy crawl csdn_spider --nolog


抓取内容我们保存在项目根目录的 csdn.txt中 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值