feed.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """
  2. This module implements the XMLFeedSpider which is the recommended spider to use
  3. for scraping from an XML feed.
  4. See documentation in docs/topics/spiders.rst
  5. """
  6. from scrapy.spiders import Spider
  7. from scrapy.utils.iterators import xmliter, csviter
  8. from scrapy.utils.spider import iterate_spider_output
  9. from scrapy.selector import Selector
  10. from scrapy.exceptions import NotConfigured, NotSupported
  11. class XMLFeedSpider(Spider):
  12. """
  13. This class intends to be the base class for spiders that scrape
  14. from XML feeds.
  15. You can choose whether to parse the file using the 'iternodes' iterator, an
  16. 'xml' selector, or an 'html' selector. In most cases, it's convenient to
  17. use iternodes, since it's a faster and cleaner.
  18. """
  19. iterator = 'iternodes'
  20. itertag = 'item'
  21. namespaces = ()
  22. def process_results(self, response, results):
  23. """This overridable method is called for each result (item or request)
  24. returned by the spider, and it's intended to perform any last time
  25. processing required before returning the results to the framework core,
  26. for example setting the item GUIDs. It receives a list of results and
  27. the response which originated that results. It must return a list of
  28. results (Items or Requests).
  29. """
  30. return results
  31. def adapt_response(self, response):
  32. """You can override this function in order to make any changes you want
  33. to into the feed before parsing it. This function must return a
  34. response.
  35. """
  36. return response
  37. def parse_node(self, response, selector):
  38. """This method must be overriden with your custom spider functionality"""
  39. if hasattr(self, 'parse_item'): # backward compatibility
  40. return self.parse_item(response, selector)
  41. raise NotImplementedError
  42. def parse_nodes(self, response, nodes):
  43. """This method is called for the nodes matching the provided tag name
  44. (itertag). Receives the response and an Selector for each node.
  45. Overriding this method is mandatory. Otherwise, you spider won't work.
  46. This method must return either a BaseItem, a Request, or a list
  47. containing any of them.
  48. """
  49. for selector in nodes:
  50. ret = iterate_spider_output(self.parse_node(response, selector))
  51. for result_item in self.process_results(response, ret):
  52. yield result_item
  53. def parse(self, response):
  54. if not hasattr(self, 'parse_node'):
  55. raise NotConfigured('You must define parse_node method in order to scrape this XML feed')
  56. response = self.adapt_response(response)
  57. if self.iterator == 'iternodes':
  58. nodes = self._iternodes(response)
  59. elif self.iterator == 'xml':
  60. selector = Selector(response, type='xml')
  61. self._register_namespaces(selector)
  62. nodes = selector.xpath('//%s' % self.itertag)
  63. elif self.iterator == 'html':
  64. selector = Selector(response, type='html')
  65. self._register_namespaces(selector)
  66. nodes = selector.xpath('//%s' % self.itertag)
  67. else:
  68. raise NotSupported('Unsupported node iterator')
  69. return self.parse_nodes(response, nodes)
  70. def _iternodes(self, response):
  71. for node in xmliter(response, self.itertag):
  72. self._register_namespaces(node)
  73. yield node
  74. def _register_namespaces(self, selector):
  75. for (prefix, uri) in self.namespaces:
  76. selector.register_namespace(prefix, uri)
  77. class CSVFeedSpider(Spider):
  78. """Spider for parsing CSV feeds.
  79. It receives a CSV file in a response; iterates through each of its rows,
  80. and calls parse_row with a dict containing each field's data.
  81. You can set some options regarding the CSV file, such as the delimiter, quotechar
  82. and the file's headers.
  83. """
  84. delimiter = None # When this is None, python's csv module's default delimiter is used
  85. quotechar = None # When this is None, python's csv module's default quotechar is used
  86. headers = None
  87. def process_results(self, response, results):
  88. """This method has the same purpose as the one in XMLFeedSpider"""
  89. return results
  90. def adapt_response(self, response):
  91. """This method has the same purpose as the one in XMLFeedSpider"""
  92. return response
  93. def parse_row(self, response, row):
  94. """This method must be overriden with your custom spider functionality"""
  95. raise NotImplementedError
  96. def parse_rows(self, response):
  97. """Receives a response and a dict (representing each row) with a key for
  98. each provided (or detected) header of the CSV file. This spider also
  99. gives the opportunity to override adapt_response and
  100. process_results methods for pre and post-processing purposes.
  101. """
  102. for row in csviter(response, self.delimiter, self.headers, self.quotechar):
  103. ret = iterate_spider_output(self.parse_row(response, row))
  104. for result_item in self.process_results(response, ret):
  105. yield result_item
  106. def parse(self, response):
  107. if not hasattr(self, 'parse_row'):
  108. raise NotConfigured('You must define parse_row method in order to scrape this CSV feed')
  109. response = self.adapt_response(response)
  110. return self.parse_rows(response)