16年一年似乎楼市经常成为热点话题啊,而现在政府多次调控,意志很坚定的样子,那么市场的反应如何呢?我们来写个爬虫吧,目标网站就是链家网。
我们在链家网上面可以看到有这些公司可以选择,所以我们的第一步就是获取每个城市的链接。
老样子,我们用xpath来获取这些城市的链接:
然后,我们只要遍历这些链接,取出我们要的数据,就是当前在售的二手房和出租的房屋就可以了。
不多说了,上代码。
首先是容器,兵马未动,粮草先行,把要收集的数据先想好了。
from scrapy.item import Item,Field
class hosueItem(Item):
city = Field()
sell = Field()
rent = Field()
newHouse = Field()
T = Field()
接下来就是怎么爬取了。
# 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
然后是数据的存储:
# -*- 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调用命令行命令,然后设置好时间,使其自动运行。
import time
import os
i = 0
while(True):
print i
os.popen("scrapy crawl houseDataSpider")
time.sleep(7200)
i = i+1
让我们的爬虫爬几天吧,之后给大家带来数据分析部分。
如果看到这里你还不能自己部署这只爬虫的话,那么看一下笔者之前关于scrapy的博客吧,了解框架才好实践哦。