本代码示例使用 Scrapy 框架爬取黑马程序员网站上的软件测试视频信息。

import scrapy
from heima_video.items import HeimaVideoItem

class SoftwareTestInfoSpider(scrapy.Spider):
    name = "software_test_info"
    allowed_domains = ["itheima.com"]
    start_urls = ["https://itheima.com/course/c144.html",]

    def parse(self, response):
        items = []  # 存储视频信息
        node_list = response.xpath('//div[contains(@class,"spjclist")' 
                                    ' and contains(@class,"spjclist1")]//ul[2]/li/a')
        basic_url = 'http://yun.itheima.com'
        for each in node_list:
            # 创建HeimaVideoItem类的对象
            item = HeimaVideoItem()
            # 使用Xpath的路径表达式选取节点
            video_name = each.xpath("./div[2]/h2/text()").getall()# 视频名称
            video_detail = each.xpath("./div[2]/p/text()").getall()# 视频描述
            students = each.xpath("./div[3]/p/span/text()").getall()#人数
            video_link = each.xpath("./@href").getall()  # 视频链接
            # 将每个视频的信息封装成HeimaVideoItem类的对象
            item["video_name"] = video_name[0]
            item["video_detail"] = video_detail[0]
            item["students"] = students[0]
            item["video_link"] = basic_url + video_link[0]
            items.append(item)
        return items
        # pass

代码说明:

  1. 导入必要的库,包括 scrapyHeimaVideoItem 类。
  2. 定义爬虫类 SoftwareTestInfoSpider,设置爬虫名称、允许的域名和起始 URL。
  3. parse 方法中,使用 XPath 选择器提取视频信息,包括视频名称、描述、报名人数和视频链接。
  4. 将提取的信息封装成 HeimaVideoItem 对象,并添加到 items 列表中。
  5. 返回 items 列表,以便 Scrapy 框架进行后续处理。

注意事项:

  1. 确保 HeimaVideoItem 类已经定义好,并且在 settings.py 文件中启用了该类。具体方法是在 ITEM_PIPELINES 字典中添加 'heima_video.pipelines.HeimaVideoPipeline': 300,其中 heima_video 为项目名称,HeimaVideoPipelinepipelines.py 中定义的管道类。
  2. 可以根据需要修改代码中的 XPath 选择器,以适应目标网站的结构变化。
  3. 运行爬虫时,需要使用 scrapy crawl software_test_info 命令。

代码示例中的错误:

代码示例本身没有明显的错误,但需要在 settings.py 文件中配置 ITEM_PIPELINES,以启用 HeimaVideoItem 类。

其他建议:

  1. 可以使用 scrapy shell 对目标网站进行调试,以确保 XPath 选择器正确无误。
  2. 可以使用 scrapy genspider 命令自动生成爬虫模板,并根据需要进行修改。
  3. 可以使用 scrapy crawl -o 命令将爬取结果保存到文件,并使用其他工具进行数据分析和可视化。
Python爬虫实战:使用Scrapy爬取黑马程序员软件测试视频信息

原文地址: https://www.cveoy.top/t/topic/n7i6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录