当前位置:   article > 正文

pyspider解析

pyspider 中response解析

https://www.cnblogs.com/microman/p/6111711.html

 

  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. # Created on 2017-12-07 13:40:43
  4. # Project: adquan
  5. from pyspider.libs.base_handler import *
  6. class Handler(BaseHandler):
  7. crawl_config = {
  8. }
  9. def __init__(self):
  10. self.deal = Deal()
  11. @every(minutes=24 * 60)
  12. def on_start(self):
  13. self.crawl('http://creative.adquan.com/show/42759', callback=self.detail_page)
  14. @config(age=10 * 24 * 60 * 60)
  15. def index_page(self, response):
  16. for each in response.doc('a[href^="http"]').items():
  17. self.crawl(each.attr.href, callback=self.detail_page)
  18. @config(priority=2)
  19. def detail_page(self, response):
  20. name = 'test'
  21. count = 0
  22. for img in response.doc('.con_Text img').items():
  23. url = img.attr.src
  24. if url:
  25. dir_path = self.deal.mkDir(name)
  26. extension = self.deal.getExtension(url)
  27. file_name = str(count) + '.' + extension
  28. count += 1
  29. self.crawl(img.attr.src, callback=self.save_img, save={'dir_path': dir_path, 'file_name':file_name})
  30. return {
  31. "url": response.url,
  32. "title": response.doc('title').text(),
  33. }
  34. def save_img(self, response):
  35. content = response.content
  36. dir_path = response.save['dir_path']
  37. file_name = response.save['file_name']
  38. file_path = dir_path + '/' + file_name
  39. self.deal.saveImg(content, file_path)
  40. import os
  41. DIR_PATH = "E:/pyspider/"
  42. class Deal:
  43. def __init__(self):
  44. self.path = DIR_PATH
  45. if not self.path.endswith('/'):
  46. self.path = self.path + '/'
  47. if not os.path.exists(self.path):
  48. os.makedirs(self.path)
  49. def mkDir(self, path):
  50. path = path.strip()
  51. dir_path = self.path + path
  52. exists = os.path.exists(dir_path)
  53. if not exists:
  54. os.makedirs(dir_path)
  55. return dir_path
  56. else:
  57. return dir_path
  58. def saveImg(self, content, path):
  59. f = open(path, 'wb')
  60. f.write(content)
  61. f.close()
  62. def saveBrief(self, content, dir_path, name):
  63. file_name = dir_path + "/" + name + ".txt"
  64. f = open(file_name, "w+")
  65. f.write(content.encode('utf-8'))
  66. def getExtension(self, url):
  67. extension = url.split('.')[-1]
  68. return extension

  http://demo.pyspider.org/

转载于:https://www.cnblogs.com/jiangjing/p/8001321.html

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

闽ICP备14008679号