当前位置:   article > 正文

用Scrapy 从数据挖掘到监控和自动化测试

用Scrapy 从数据挖掘到监控和自动化测试

Scrapy 是一个 BSD 许可的快速高级网络爬虫和网络抓取框架,用于抓取网站并从其页面中提取结构化数据。它可以用于广泛的用途,从数据挖掘到监控和自动化测试。

安装scrapy

pip install scrapy

爬虫示例

示例代码写入文件

  1. import scrapy
  2. class QuotesSpider(scrapy.Spider):
  3. name = "quotes"
  4. start_urls = [
  5. "https://quotes.toscrape.com/tag/humor/",
  6. ]
  7. def parse(self, response):
  8. for quote in response.css("div.quote"):
  9. yield {
  10. "author": quote.xpath("span/small/text()").get(),
  11. "text": quote.css("span.text::text").get(),
  12. }
  13. next_page = response.css('li.next a::attr("href")').get()
  14. if next_page is not None:
  15. yield response.follow(next_page, self.parse)

执行

scrapy runspider quotes_spider.py -o quotes.jsonl

可以看到执行结果如下:

  1. scrapy runspider quotes_spider.py -o quotes.jsonl
  2. 2024-05-01 22:10:19 [scrapy.utils.log] INFO: Scrapy 2.11.1 started (bot: scrapybot)
  3. 2024-05-01 22:10:19 [scrapy.utils.log] INFO: Versions: lxml 4.6.3.0, libxml2 2.11.6, cssselect 1.2.0, parsel 1.9.1, w3lib 2.1.2, Twisted 24.3.0, Python 3.10.13 (main, Nov 9 2023, 03:04:43) [Clang 14.0.5 (https://github.com/llvm/llvm-project.git llvmorg-14.0.5-0-gc12386, pyOpenSSL 24.1.0 (OpenSSL 1.1.1t-freebsd 7 Feb 2023), cryptography 42.0.5, Platform FreeBSD-13.2-RELEASE-p10-amd64-64bit-ELF
  4. 2024-05-01 22:10:19 [scrapy.addons] INFO: Enabled addons:
  5. []
  6. 2024-05-01 22:10:19 [py.warnings] WARNING: /usr/home/skywalk/py310/lib/python3.10/site-packages/scrapy/utils/request.py:254: ScrapyDeprecationWarning: '2.6' is a deprecated value for the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting.
  7. It is also the default value. In other words, it is normal to get this warning if you have not defined a value for the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting. This is so for backward compatibility reasons, but it will change in a future version of Scrapy.
  8. See the documentation of the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting for information on how to handle this deprecation.
  9. return cls(crawler)
  10. 2024-05-01 22:10:19 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.pollreactor.PollReactor
  11. 2024-05-01 22:10:19 [scrapy.extensions.telnet] INFO: Telnet Password: 18295d3f4c994eee
  12. 2024-05-01 22:10:19 [scrapy.middleware] INFO: Enabled extensions:
  13. ['scrapy.extensions.corestats.CoreStats',
  14. 'scrapy.extensions.telnet.TelnetConsole',
  15. 'scrapy.extensions.memusage.MemoryUsage',
  16. 'scrapy.extensions.feedexport.FeedExporter',
  17. 'scrapy.extensions.logstats.LogStats']
  18. 2024-05-01 22:10:19 [scrapy.crawler] INFO: Overridden settings:
  19. {'SPIDER_LOADER_WARN_ONLY': True}
  20. 2024-05-01 22:10:20 [scrapy.middleware] INFO: Enabled downloader middlewares:
  21. ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
  22. 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
  23. 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
  24. 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
  25. 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
  26. 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
  27. 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
  28. 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
  29. 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
  30. 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
  31. 'scrapy.downloadermiddlewares.stats.DownloaderStats']
  32. 2024-05-01 22:10:20 [scrapy.middleware] INFO: Enabled spider middlewares:
  33. ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
  34. 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
  35. 'scrapy.spidermiddlewares.referer.RefererMiddleware',
  36. 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
  37. 'scrapy.spidermiddlewares.depth.DepthMiddleware']
  38. 2024-05-01 22:10:20 [scrapy.middleware] INFO: Enabled item pipelines:
  39. []
  40. 2024-05-01 22:10:20 [scrapy.core.engine] INFO: Spider opened

完成此操作后, quotes.jsonl 文件中将包含JSON行格式的引号列表,其中包含文本和作者,如下所示:

  1. {"author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not
  2. pleasure in a good novel, must be intolerably stupid.\u201d"}
  3. {"author": "Steve Martin", "text": "\u201cA day without sunshine is like, you know, night
  4. .\u201d"}
  5. {"author": "Garrison Keillor", "text": "\u201cAnyone who thinks sitting in church can mak
  6. e you a Christian must also think that sitting in a garage can make you a car.\u201d"}
  7. {"author": "Jim Henson", "text": "\u201cBeauty is in the eye of the beholder and it may b
  8. e necessary from time to time to give a stupid or misinformed beholder a black eye.\u201d
  9. "}

监控

日志监控:Scrapy 提供了强大的日志系统,可以通过查看日志来监控爬虫的运行状态,也可以通过日志分析出被监控网站的运行状态。

自动化测试

Spider 编写测试,可以模拟 HTTP 响应,并验证 Spider 是否能够正确解析这些数据。

ps scapy是一个包处理软件。可以参考这篇文档学习:通过摆弄python scapy模块 了解网络模型--Get your hands dirty! - 知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/547797
推荐阅读
相关标签
  

闽ICP备14008679号