经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
scrapy实例:爬取安居客租房信息
来源:cnblogs  作者:forHeart_toHeart  时间:2018/10/22 16:28:47  对本文有异议

本次爬取安居客网站,获取上海长宁区的租房信息,参考自:微信公众号

仍然是用scrapy框架构建爬虫,步骤:1.分析网页

                 2.items.py

                 3.spiders.py

                 4. pipelines.py

                 5.settings.py

  • 观察网页

                 上海长宁区租房信息: https://sh.zu.anjuke.com/fangyuan/changning/

  • items.py

      这里定义字段保存要爬取的信息

  1. price ========= scrapy.Field()
  • spider.py

    这里编写爬虫文件,告诉爬虫要爬取什么,怎么爬取

  1. import scrapyfrom scrapy.spiders import Rulefrom scrapy.linkextractors import LinkExtractorfrom anjukeSpider.items import AnjukespiderItem# 定义爬虫类class anjuke(scrapy.spiders.CrawlSpider):#爬虫名称name = 'anjuke'#爬虫起始网页start_urls = ['https://sh.zu.anjuke.com/fangyuan/changning/']#爬取规则rules = (
  2.                 Rule(LinkExtractor(allow=r'fangyuan/p\d+/'), follow=True), #网页中包含下一页按钮,所以这里设置True爬取所有页面Rule(LinkExtractor(allow=r'https://sh.zu.anjuke.com/fangyuan/\d{10}'), follow=False, callback='parse_item'),#网页里含有【推荐】的房源信息但不一定是我们想要的长宁区,所以设置False不跟进            )#回调函数,主要就是写xpath路径,上一篇实例说过,这里就不赘述了def parse_item(self, response):
  3.         item = AnjukespiderItem()# 租金item['price'] = int(response.xpath("//ul[@class='house-info-zufang cf']/li[1]/span[1]/em/text()").extract_first())# 出租方式item['rent_type'] = response.xpath("//ul[@class='title-label cf']/li[1]/text()").extract_first()# 户型item['house_type'] = response.xpath("//ul[@class='house-info-zufang cf']/li[2]/span[2]/text()").extract_first()# 面积item['area'] = int(response.xpath("//ul[@class='house-info-zufang cf']/li[3]/span[2]/text()").extract_first().replace('平方米',''))# 朝向item['towards'] = response.xpath("//ul[@class='house-info-zufang cf']/li[4]/span[2]/text()").extract_first()# 楼层item['floor'] = response.xpath("//ul[@class='house-info-zufang cf']/li[5]/span[2]/text()").extract_first()# 装修item['decoration'] = response.xpath("//ul[@class='house-info-zufang cf']/li[6]/span[2]/text()").extract_first()# 住房类型item['building_type'] = response.xpath("//ul[@class='house-info-zufang cf']/li[7]/span[2]/text()").extract_first()# 小区item['community'] = response.xpath("//ul[@class='house-info-zufang cf']/li[8]/a[1]/text()").extract_first()yield item
  • pipelines.py

    保存爬取的数据,这里只保存为json格式

    其实可以不写这部分,不写pipeline ,运行时加些参数:scrapy crawl anjuke -o anjuke.json -t json

                             scrapy crawl 爬虫名称 -o 目标文件名称 -t 保存格式

  1. from scrapy.exporters import JsonItemExporterclass AnjukespiderPipeline(object):def __init__(self):
  2.         self.file = open('zufang_shanghai.json', 'wb') #设置文件存储路径self.exporter = JsonItemExporter(self.file, ensure_ascii=False)
  3.         self.exporter.start_exporting()def process_item(self, item, spider):print('write')
  4.         self.exporter.export_item(item)return itemdef close_spider(self, spider):print("close")
  5.         self.exporter.finish_exporting()
  6.         self.file.close()
  • settings.py

    修改settings文件,使pipeline生效

    设置下载延迟,防止访问过快导致被网站屏蔽

  1. ITEM_PIPELINES = {'anjukeSpider.pipelines.AnjukespiderPipeline': 300,
  2. }
  3.  
  4. DOWNLOAD_DELAY = 2

 

  • 运行命令行,进入项目根目录,键入

    1. scrapy crawl [爬虫名称]
    1. PS F:\ScrapyProject\anjukeSpider\anjukeSpider> scrapy crawl anjuke

    执行完成

    爬取到61条信息,json文件在指定路径已生成

    1. 2018-10-22 09:02:55 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
    2. {'downloader/request_bytes': 40861, 'downloader/request_count': 61, 'downloader/request_method_count/GET': 61, 'downloader/response_bytes': 1925879, 'downloader/response_count': 61, 'downloader/response_status_count/200': 61, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2018, 10, 22, 1, 2, 55, 245128), 'item_scraped_count': 60, 'log_count/DEBUG': 122, 'log_count/INFO': 9, 'request_depth_max': 1, 'response_received_count': 61, 'scheduler/dequeued': 61, 'scheduler/dequeued/memory': 61, 'scheduler/enqueued': 61, 'scheduler/enqueued/memory': 61, 'start_time': datetime.datetime(2018, 10, 22, 1, 0, 29, 555537)}2018-10-22 09:02:55 [scrapy.core.engine] INFO: Spider closed (finished)

    爬虫到此完成,但爬取到的数据并不直观,还需对其做可视化处理(pyecharts模块),这部分另写一篇pyecharts使用

  • pyecharts官方文档:http://pyecharts.org/#/zh-cn/

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号