使用 Scrapy 在 Python 中实现 Web 抓取

pythonserver side programmingprogramming更新于 2025/11/16 17:16:17

在本文中,我们将学习使用 Python 中提供的 Scrappy 模块的 Web 抓取技术。

什么是 Web 抓取?

Web 抓取用于在爬虫/扫描仪的帮助下从网站获取数据。Web 抓取非常方便,可以从不提供 API 功能的网页中提取数据。在 Python 中,可以借助 Beautiful Soup、Scrappy 和 lxml 等各种模块进行 Web 抓取。

在这里,我们将讨论使用 Scrappy 模块进行 Web 抓取。

为此,我们首先需要安装 Scrappy。

在终端或命令提示符中输入 −

>>> pip install Scrappy

由于 Scrappy 是一个框架,因此我们需要运行一个初始化命令

>>> scrappy startproject tutpts

在这里,我们创建一个网络爬虫/蜘蛛来从网站中获取数据。

为了构建爬虫,我们创建了一个名为tutptscraw.py的单独脚本。在这里,我们声明一个用于提取内容的类。在这里,我们命名网络爬虫并使用 .requests 从给定的 URL 获取数据。

使用生成器函数来生成获取的数据。

import scrapy
class ExtractUrls(scrapy.Spider):
   name = "fetch"
   # generator Function
   def start_requests(self):
      # enter the URL
      urls = ['https://www.tutorialspoint.com/index.htm/', ]
      for url in urls:
         yield scrapy.Request(url = url, callback = self.parse)

这里使用请求函数获取锚标记内封装的所有数据。由于 scrappy 是一个小型框架,因此我们在 scrappy shell 中运行所有功能。

要激活 scrap shell,我们使用以下命令

scrappy shellscrapy shell https://www.tutorialspoint.com/index.htm

现在我们使用选择器(即 CSS 或 xpath)从锚标记获取数据

response.css('a')
links = response.css('a').extract()

为了获取网页上所有可用的链接,我们创建了一个解析方法。Scrappy 在内部绕过以前访问过的 URL,从而减少显示结果时的渲染时间。

import scrapy
class ExtractUrls(scrapy.Spider):
   name = "fetch"
   # generator Function
   def start_requests(self):
      # enter the URL
      urls = ['https://www.tutorialspoint.com/index.htm/', ]
      for url in urls:
         yield scrapy.Request(url = url, callback = self.parse)
   # Parse function
   def parse(self, response):
      title = response.css('title::text').extract_first()
      # Get anchor tags
      links = response.css('a::attr(href)').extract()
      for link in links:
         yield {
            'title': title,
            'links': link
         }
         if 'tutorialspoint' in link:
            yield scrapy.Request(url = link, callback = self.parse)

结论

在本教程中,我们学习了使用 python 中的 Scrappy 模块实现网络爬虫


相关文章


有用资源