当前位置:   article > 正文

用Scrapy抓取当当网站数据_使用scrapy爬取当当网数据

使用scrapy爬取当当网数据

setting.py实验目的及要求:

实验目的

     通过本实验了解Scrapy爬虫框架;熟练掌握Scrapy的基本使用方法和常用技巧。

实验要求

     使用Scrapy框架,抓取网站商品信息(京东、淘宝、当当等任选一个),并将结果保存成多种形式。(本文选择当当)

实验原理及内容:

实验原理】(列出相关知识点)

  1. Scrapy框架:
    • 理解Scrapy框架的基本原理和架构。
  2. HTTP请求和响应:
    • 理解HTTP请求和响应的基本概念。
    • 如何通过Scrapy发送HTTP请求和处理响应。
  3. Web页面结构:
    • 了解HTML和CSS的基础知识,理解Web页面的结构。
  4. CSS选择器和XPath:
    • 使用CSS选择器或XPath在网页中定位和提取信息。
  5. Scrapy Spider:
    • 创建Scrapy Spider,定义如何抓取和解析页面。
    • 如何通过Spider跟踪链接和处理分页。
  6. Scrapy Items:
    • 定义Scrapy Items,用于存储抓取的数据。
  7. Scrapy Pipelines:
    • 编写Scrapy Pipelines处理抓取到的Item。
    • 配置Pipeline在settings.py中。
  8. 异常处理:
    • 处理可能出现的异常,例如超时、连接错误等。
  9. 数据存储:
    • 将抓取到的数据保存到不同的存储介质,如文件、数据库等。
  10. 用户代理和IP代理:
    • 设置和使用用户代理和IP代理,以避免被封禁。
  11. 异步和并发:
    • 配置异步和并发请求以提高爬取效率。
  12. Scrapy Settings:
    • 配置Scrapy的Settings,包括用户代理、下载延迟等。
  13. Web爬取伦理:
    • 了解爬虫的伦理和法律问题,避免对网站造成不必要的压力。
  14. 日志和调试:
    • 使用Scrapy的日志系统进行调试。
  15. 扩展和定制:
    • 定制和扩展Scrapy,满足特定需求。

程序思路

  1. 首先,因为我们要抓取网页中的标题、链接和评论数,所以我们首先得写items.py
  2. 在这里添加完我们需要爬取的哪些数据后,我们在转向我们的爬虫文件,我们通过 scrapy genspider dd dangdang.com 创建了一个爬虫文件dd.py
  3. 然后开始撰写settings.py
  4. 最后编写pipelines.py文件了(也就是可以正式操作数据了)。

 实验数据与结果分析:(含运行结果截屏)

【实验结果】

【结果分析】

         利用Scrapy框架抓取了当当网站商品信息,并通过ppline.py将数据存储到了mysql数据库中,可以以不同数据存储方式存储。

实验小结:(包括问题和解决方法、心得体会、意见与建议等)

         在进行这个实验的过程中,我首先面临的挑战是网站结构的变化。由于当当网站可能会定期更新,导致之前编写的爬虫代码无法正确提取信息。为了解决这个问题,我学习了如何动态调整选择器以适应变化的网页结构,并通过查看网页源代码来快速调整选择器,确保爬虫的准确性。

         在实验中,我深刻体会到Scrapy框架的强大之处。通过定义Item、编写Spider、配置Pipeline等步骤,我成功地构建了一个功能强大的爬虫,能够高效地抓取和处理目标网站的信息。学会使用Scrapy的中间件和设置,我更好地掌握了爬虫的并发和异步请求的处理方式,提高了爬取效率。

         通过实验,我还发现了对数据进行实时分析和监控的重要性。及时发现并解决异常情况,如数据缺失、异常格式等,有助于提高爬虫的稳定性。此外,通过对数据进行统计和可视化分析,我更全面地了解了抓取到的信息,发现了一些潜在的趋势和规律。通过这个实验,我不仅掌握了Scrapy框架的使用,还培养了解决实际问题的能力,让我受益匪浅。

实验源代码清单:(带注释)

item.py:

  1. # Define here the models for your scraped items
  2. #
  3. # See documentation in:
  4. # https://docs.scrapy.org/en/latest/topics/items.html
  5. import scrapy
  6. class DangdangItem(scrapy.Item):
  7. # define the fields for your item here like:
  8. # name = scrapy.Field()
  9. title = scrapy.Field()
  10. link = scrapy.Field()
  11. price = scrapy.Field()
  12. shop = scrapy.Field()
  1. # Scrapy settings for dangdang project
  2. #
  3. # For simplicity, this file contains only settings considered important or
  4. # commonly used. You can find more settings consulting the documentation:
  5. #
  6. # https://docs.scrapy.org/en/latest/topics/settings.html
  7. # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
  8. # https://docs.scrapy.org/en/latest/topics/spider-middleware.html
  9. BOT_NAME = 'dangdang'
  10. SPIDER_MODULES = ['dangdang.spiders']
  11. NEWSPIDER_MODULE = 'dangdang.spiders'
  12. # Crawl responsibly by identifying yourself (and your website) on the user-agent
  13. USER_AGENT = {
  14. 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
  15. }
  16. # Obey robots.txt rules
  17. ROBOTSTXT_OBEY = False
  18. LOG_LEVEL = 'ERROR'
  19. # Configure maximum concurrent requests performed by Scrapy (default: 16)
  20. #CONCURRENT_REQUESTS = 32
  21. # Configure a delay for requests for the same website (default: 0)
  22. # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
  23. # See also autothrottle settings and docs
  24. #DOWNLOAD_DELAY = 3
  25. # The download delay setting will honor only one of:
  26. #CONCURRENT_REQUESTS_PER_DOMAIN = 16
  27. #CONCURRENT_REQUESTS_PER_IP = 16
  28. # Disable cookies (enabled by default)
  29. #COOKIES_ENABLED = False
  30. # Disable Telnet Console (enabled by default)
  31. #TELNETCONSOLE_ENABLED = False
  32. # Override the default request headers:
  33. #DEFAULT_REQUEST_HEADERS = {
  34. # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  35. # 'Accept-Language': 'en',
  36. #}
  37. # Enable or disable spider middlewares
  38. # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
  39. #SPIDER_MIDDLEWARES = {
  40. # 'dangdang.middlewares.DangdangSpiderMiddleware': 543,
  41. #}
  42. # Enable or disable downloader middlewares
  43. # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
  44. DOWNLOADER_MIDDLEWARES = {
  45. 'dangdang.middlewares.DangdangDownloaderMiddleware': 543,
  46. }
  47. # Enable or disable extensions
  48. # See https://docs.scrapy.org/en/latest/topics/extensions.html
  49. #EXTENSIONS = {
  50. # 'scrapy.extensions.telnet.TelnetConsole': None,
  51. #}
  52. # Configure item pipelines
  53. # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
  54. ITEM_PIPELINES = {
  55. 'dangdang.pipelines.DangdangPipeline': 300,
  56. }
  57. # Enable and configure the AutoThrottle extension (disabled by default)
  58. # See https://docs.scrapy.org/en/latest/topics/autothrottle.html
  59. #AUTOTHROTTLE_ENABLED = True
  60. # The initial download delay
  61. #AUTOTHROTTLE_START_DELAY = 5
  62. # The maximum download delay to be set in case of high latencies
  63. #AUTOTHROTTLE_MAX_DELAY = 60
  64. # The average number of requests Scrapy should be sending in parallel to
  65. # each remote server
  66. #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
  67. # Enable showing throttling stats for every response received:
  68. #AUTOTHROTTLE_DEBUG = False
  69. # Enable and configure HTTP caching (disabled by default)
  70. # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
  71. #HTTPCACHE_ENABLED = True
  72. #HTTPCACHE_EXPIRATION_SECS = 0
  73. #HTTPCACHE_DIR = 'httpcache'
  74. #HTTPCACHE_IGNORE_HTTP_CODES = []
  75. #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
'
运行

Pipline.py

  1. # Define your item pipelines here
  2. #
  3. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  4. # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
  5. # useful for handling different item types with a single interface
  6. #from itemadapter import ItemAdapter
  7. #from pymongo import MongoClient
  8. class DangdangPipeline:
  9. def __init__(self):
  10. self.client = MongoClient(host='localhost',port=27017)
  11. self.db = self.client['当当']
  12. self.collections = self.db['python爬虫']
  13. def process_item(self, item, spider):
  14. data = {
  15. 'title': item['title'],
  16. 'link': item['link'],
  17. 'price': item['price'],
  18. 'shop': item['shop'],
  19. }
  20. print(data)
  21. self.collections.insert(data)
  22. return item
'
运行

dd.py

  1. import scrapy
  2. from dangdang.items import DangdangItem
  3. class DdSpider(scrapy.Spider):
  4. name = 'dd'
  5. # allowed_domains = ['www.dangdang.com']
  6. start_urls = ['http://search.dangdang.com/?key=python%C5%C0%B3%E6&act=input&page_index=1']
  7. def parse(self, response):
  8. item = DangdangItem()
  9. li_lists = response.xpath('//*[@id="component_59"]/li')
  10. for li_list in li_lists:
  11. title = li_list.xpath('./p[1]/a/@title').extract()[0]
  12. link = 'http:'+li_list.xpath('./p[1]/a/@href').extract()[0]
  13. price = li_list.xpath('./p[3]/span/text()').extract()[0]
  14. shop = li_list.xpath('./p[4]/a/text()').extract()[0]
  15. item['title'] = title
  16. item['link'] = link
  17. item['price'] = price
  18. item['shop'] = shop
  19. # print(title)
  20. # print(link)
  21. # print(price)
  22. # print(shop)
  23. # print('*'*100)
  24. yield item
  25. for page in range(2,101):
  26. url = f'http://search.dangdang.com/?key=python%C5%C0%B3%E6&act=input&page_index={page}'
  27. result = scrapy.Request(url,callback=self.parse)
  28. yield result

项目总结构为:

               

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

闽ICP备14008679号