前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >想炒房?你得会爬虫

想炒房?你得会爬虫

作者头像
钱塘小甲子
发布2019-01-28 15:27:05
2990
发布2019-01-28 15:27:05
举报

16年一年似乎楼市经常成为热点话题啊,而现在政府多次调控,意志很坚定的样子,那么市场的反应如何呢?我们来写个爬虫吧,目标网站就是链家网。

我们在链家网上面可以看到有这些公司可以选择,所以我们的第一步就是获取每个城市的链接。

老样子,我们用xpath来获取这些城市的链接:

然后,我们只要遍历这些链接,取出我们要的数据,就是当前在售的二手房和出租的房屋就可以了。

不多说了,上代码。

首先是容器,兵马未动,粮草先行,把要收集的数据先想好了。

代码语言:javascript
复制
from scrapy.item import Item,Field  
  
class hosueItem(Item):  
    city = Field()  
    sell = Field()
    rent = Field()
    newHouse = Field()
    T  = Field()

接下来就是怎么爬取了。

代码语言:javascript
复制
# coding=gbk
from scrapy.spiders import Spider  
from scrapy.selector import Selector  
import scrapy
import time
#from scrapy import log  
  
from housePrice.items import hosueItem  
 
  
class houseSpider(Spider):  
   
	name = "houseDataSpider"  
	start_urls = [  
		"https://hz.lianjia.com/"  
	]  #start url at the first page
    
    
	def parse(self, response): #这个是spider类中默认的方法,我们做一个重写,response就是那个html文件哦。
		sel = Selector(response)  #获取了所有的连接
		cityLinkList = sel.xpath('/html/body/div[1]/div/div[2]/div[3]/div/ul/li/div/a/@href').extract()
		#print cityLinkList
		#cityNameList = sel.xpath('/html/body/div[1]/div/div[2]/div[3]/div/ul/li/div/a/text()').extract()
		for link in cityLinkList:#每个链接送到下面一个回调函数中
			yield scrapy.Request(link, callback=self.getDetailParse)
       
	def getDetailParse(self, response):
		sel = Selector(response)   
		item = hosueItem() 
		#xpath获得数据        
		str1 = sel.xpath('/html/body/div[1]/div/div[5]/div[2]/ul/li[1]/text()').extract()  
		str2 = sel.xpath('/html/body/div[1]/div/div[5]/div[2]/ul/li[2]/text()').extract()
		str3 = sel.xpath('/html/body/div[1]/div/div[5]/div[2]/ul/li[3]/text()').extract()

        #item['city'] = city
		item['sell'] = [t.encode('utf-8') for t in str1]  
		item['rent'] = [t.encode('utf-8') for t in str2]  
		item['newHouse'] = [t.encode('utf-8') for t in str3]             
		item['T'] = time.localtime()[3]            
	
		yield item

然后是数据的存储:

代码语言:javascript
复制
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json  
import codecs  
import time
  
class housePipeline(object):  
    	def __init__(self):  
    		timest = str(time.localtime()[0])+'-'+str(time.localtime()[1])+'-'+str(time.localtime()[2])+'-'+str(time.localtime()[3])+'-'+str(time.localtime()[4])
        	self.file = codecs.open(timest+'house.json', 'wb', encoding='utf-8')  
  
	def process_item(self, item, spider): 
       # if item['salary'] == [] or item['location1'] == [] or item['jobDesc'] == [] or item['jobType']==[] or  item['degree']==[]:
        	#return item
        #else:
		if item['sell']  != []:
			#city = [item['sell'][0][0]+item['sell'][0][1]]
			line = ','.join(item['sell'] + item['rent'])+','+str(item['T'])  + "\n"
        # print line  
			self.file.write(line.decode("utf-8"))  
       		return item  

这里,我们注意到,文件的命名是根据时间不同而不同的,我们稍后是希望每隔一段时间,爬虫自动运行。

完成配置文件后我们就可以运行了,大概是这样的效果:

到这里,爬虫就完成了,接下来,我们希望每隔两小时,爬虫自动运行一次。

很显然,我们运行爬虫用的是windows的命令行,所以我们可以用python调用命令行命令,然后设置好时间,使其自动运行。

代码语言:javascript
复制
import time
import os
i = 0
while(True):
    print i
    os.popen("scrapy crawl houseDataSpider")
    time.sleep(7200)
    i = i+1

让我们的爬虫爬几天吧,之后给大家带来数据分析部分。

如果看到这里你还不能自己部署这只爬虫的话,那么看一下笔者之前关于scrapy的博客吧,了解框架才好实践哦。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年11月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档