Python爬虫实战之利用Scrapy框架爬取传智播客课程数据

1.文件结构:
在这里插入图片描述
2.lesson.py代码

import scrapy
from ts.items import TsItem
from scrapy.http import Request


class LessonSpider(scrapy.Spider):
    name = 'lesson'
    allowed_domains = ['hellobi.com']
    start_urls = ['https://edu.hellobi.com/course/1']
    def parse(self, response):
        item=TsItem()
        item['title']=response.xpath("//ol[@class='breadcrumb']/li[@class='active']/text()").extract()
        item['link'] = response.xpath("//ul[@class='nav nav-tabs']/li[@class='active']/a/@href").extract()
        item['stu'] = response.xpath("//span[@class='course-view']/text()").extract()
        yield item
        for i in range(2,121): #控制课程数
            url='https://edu.hellobi.com/course/'+str(i)
            yield Request(url,callback=self.parse)

3.item.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 TsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title=scrapy.Field()
    link=scrapy.Field()
    stu=scrapy.Field()

4.pipelines.py代码

class TsPipeline(object):
    def __init__(self):
        self.fh=open("D:/软件(学习)/Python/Test/chapter8/result/ts.txt","a")

    def process_item(self, item, spider):
        print(item['title'])
        print(item['link'])
        print(item['stu'])
        print('~~~~~~')
        self.fh.write(item['title'][0]+"\n"+item['link'][0]+"\n"+item['stu'][0]+"\n"+"~~~~~~~"+"\n")
        return item

    def close_spider(self):
        self.fh.close()

5.setting.py代码

BOT_NAME = 'ts'

SPIDER_MODULES = ['ts.spiders']
NEWSPIDER_MODULE = 'ts.spiders'
...
ROBOTSTXT_OBEY = True
...
ITEM_PIPELINES = {
    'ts.pipelines.TsPipeline': 300,
}

TXT文件展示:
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值