Python数据爬虫学习笔记(18)Scrapy天善智能网课信息爬虫

一、需求:爬取天善智能网站中的所有网课的信息,包括网课名称、学习人数以及链接。

二、Scrapy实现思路:使用传统的方法,找寻每个网课的URL规律,使用for循环来循环爬取网课网页的信息。

三、URL及源代码分析:

1、URL分析,注意到网课的URL由+网课编号组成,不断更换网课编号进行测试注意到,网课编号是连续的且最大值为294(截至发博文的日期)。

2、源代码分析,观察网课网页中的源代码,找寻其中的网课名称、学习人数以及网课链接所在的源码标签结构,若源码中出现多次,则选取最易构建XPath表达式的:

    1)网课名称

    2)学习人数

扫描二维码关注公众号,回复: 3755395 查看本文章

    3)网课链接

四、编写代码:

1、items.py:

import scrapy
class TsprojectItem(scrapy.Item):
    #网课标题
    title=scrapy.Field()
    #网课链接
    link=scrapy.Field()
    #网课学习人数
    stu=scrapy.Field()

2、pipelines.py:

class TsprojectPipeline(object):
    #设置爬取的数据存储在TXT文件中
    def __init__(self):
        self.fh=open("E:/Scrapy/result/1.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()

3、settings.py:

ITEM_PIPELINES = {
    'tsproject.pipelines.TsprojectPipeline': 300,
}

4、tsSpider.py(创建的爬虫文件):

import scrapy
from tsproject.items import TsprojectItem
from scrapy.http import Request

class TsspiderSpider(scrapy.Spider):
    name = 'tsSpider'
    allowed_domains = ['hellobi.com']
    #起始爬虫网址
    start_urls = ['https://edu.hellobi.com/course/1']
    #解析数据方法
    def parse(self, response):
        item=TsprojectItem()
        #设置XPath表达式进行爬取
        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()
        #传递item
        yield  item
        for i in range(0,295):
            # 构建新url进行传递,并设定解析函数仍为parse
            url="https://edu.hellobi.com/course/"+str(i)
            yield Request(url,callback=self.parse)

五、运行结果:

    1)cmd中的运行结果(本博文使用PowerShell代替):

    2)文件中的运行结果:

感谢韦玮老师的指导

猜你喜欢

转载自blog.csdn.net/Smart3S/article/details/82941255