前言
我们要买房子,当然是要到人多的地方买,这样才热闹,如果买到人气不旺的地方搞不好会得抑郁症,出于这个目的,我们要制作一个二手房爬虫,并调用百度api了解哪个地区房子热门.
设计
- 爬取链家二手房数据
- 调用百度地图api,根据二手房地址,获取经纬度坐标
- 通过经纬度坐标和关注热度,再次调用百度地图api绘制热力图
网页分析
因为链家的数据并没有通过js渲染,不是ajax加载,所以数据提取过程非常简单,直接去网页寻找就行.这里就不分析了.
具体实现
通过https://www.lianjia.com/city/网址获取所有城市名对应的代号,以便爬取不同的城市.
def getCityCodeList(): url='https://www.lianjia.com/city/' res=requests.get(url,headers=header) doc=pq(res.text) pattern=re.compile(r'<a\shref=["|'].//(\w{2}).*">(.)<') cityCodeList={} aList=doc('.city_list_ul a').items() for a in aList: matcher=pattern.match(str(a)) cityCodeList[(matcher.group(2))]=matcher.group(1) return cityCodeList
创建一个解析房屋信息的函数
def parseHouseInfo(text): houseInfoList=[] doc=pq(text) infoList=doc('.sellListContent li').items() for info in infoList: #小区名地址address subAddress=[i.text() for i in info('.positionInfo').items('a')] address=subAddress[1]+subAddress[0] #热度hot hot=re.findall(r'^(\d+)人',info('.followInfo').text())[0] #样式style,面积space (style,space,abandon)=re.findall(r'(\d{1}室\d{1}厅).*\s(\d+(.\d+)?平米)',info('.houseInfo').text())[0] #价格price price=info('.totalPrice span').text()+'万' houseInfoList.append((address,hot,style,space,price)) return houseInfoList
调用上面两个方法,解析出我们想要城市的房屋信息,并写入csv文件
def crawlToFile(city,pg=100): houseFile = open(city+'.csv','w',newline='') houseHeader=['address','location','hot','style','space','price'] csvWriter=DictWriter(houseFile,houseHeader) csvWriter.writeheader() cityCodeList=getCityCodeList() cityCode=cityCodeList[city] baseUrl='https://'+cityCode+'.lianjia.com/ershoufang/pg' for i in range(1,pg+1): res=requests.get(baseUrl+str(i),headers=header) time.sleep(1) # (小区地址,热度,房屋样式(几室几厅),房屋大小,房价) houseInfoList=parseHouseInfo(res.text) for houseInfo in houseInfoList: address,hot,style,space,price = houseInfo location=getLocation(city,address) houseRow={ 'address':address, 'location':location, 'hot':hot, 'style':style, 'space':space, 'price':price } csvWriter.writerow(houseRow) houseFile.close()(www.hedaoshe.com)
根据csv文件,提取出我们想要的经纬度和热度信息,保存到json文件中
def getHotMapData(filepath): hotMapData=[] with open(filepath) as houseInfo: reader=csv.reader(houseInfo) for row in reader: lngAndLat=row[1].split(',') if len(lngAndLat)==2: lng=float(lngAndLat[0]) lat=float(lngAndLat[1]) hot=int(re.findall(r'\d+',row[5])[0]) subData={'lng':lng,'lat':lat,'count':hot} hotMapData.append(subData) hotMapJson=json.dumps(hotMapData) with open('hotMap.json','w') as hotMapFile: hotMapFile.write("var points="+hotMapJson)
使用百度提供的绘制热力图网页,导入我们的json数据,绘制成热力图.这个页面是复制粘贴过来的,不需要了解,只需要使用就行.
热力图功能示例
百度热力图页面基本设置
![]()
以上只是基本设置,具体可以参照百度地图api文档
完整的实例代码可以去我的github下载
结束语
- 通过以上步骤,我们就能知道哪个小区人们关注度高.团结就是力量,人越多的地方力量越大.
- 这个爬虫只是一个简单demo,可以发挥我们的想象,把它变成房屋信息全能蜘蛛.奥利干!