吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4353|回复: 13
收起左侧

[Python 转载] 北京地区二手房爬虫数据处理与展示

  [复制链接]
zyt温柔发 发表于 2019-6-15 22:32
业余时间学的python,写的是关于北京的二手房爬虫,从数据的爬取,清洗,存取到数据可视化,然后利用sklearn的线性回归算法做了一个关于房价面积的预测,欢迎大家一块学习交流。

https://github.com/zhaoyuetong/python



部分图片展示:
EXCJYS46Z(1CLPL68TE46]C.png
I(I@`]2RTGYJ6A@LMJIV)[P.png NQ3$SBSJ@NHVL1YT[T5HE_P.png W3%7`X799}]TQ)M0M@DA%NL.png
二手房户型和关注人数分布.jpg 二手房面积分布.jpg 各个区域房源均价.jpg
北京二手房与面积的房价预测.png


部分代码展示:
[Python] 纯文本查看 复制代码
#导入相关库
import requests
import time
from bs4 import BeautifulSoup
import pandas as pd
#设置页面页的可变部分
page=('pg')
#设置请求头部信息
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html;q=0.9,*/*;q=0.8',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding':'gzip',
'Connection':'close',
'Referer':'http://www.baidu.com/link?url=_andhfsjjjKRgEWkj7i9cFmYYGsisrnm2A-TN3XZDQXxvGsM9k9ZZSnikW2Yds4s&wd=&eqid=c3435a7d00006bd600000003582bfd1f'
}
def main():
    #设置列表页URL的固定部分
    url='https://bj.lianjia.com/ershoufang/'
    a=(url+page+'/')
    r=requests.get(url=a,headers=headers)
    html=r.content
    #解析抓取的页面内容
    lj=BeautifulSoup(html,'html.parser')
    positionInfo=lj.find_all('div',attrs={'class':'section_sub_nav'})
    #print(return_regin(positionInfo))
    positionInfo = return_regin(positionInfo)
    #print(positionInfo)
    for regin in positionInfo:
        regin1 =regin
        url1 = url+regin
        Crawling_data(url1,is_sellect(regin),regin1)
    pass 
#Crawling_data(url,positionInfo)
#h获取北京各个区
def return_regin(positionInfo):
    a_lis = []
    for item in positionInfo:
         pzzr=item.find_all('a')
         #print(pzzr)
         for item in pzzr:
             a_lis.append(item.get("href").split('/')[-2])
    a_lis.pop()
    return a_lis  
    pass
#判断当前选择的区
def is_sellect(regin):
    url='https://bj.lianjia.com/ershoufang/'+regin+'/'
    a=(url+page+'/')
    r=requests.get(url=a,headers=headers)
    html=r.content
    #解析抓取的页面内容
    lj=BeautifulSoup(html,'html.parser')
    positionInfo=lj.find_all('div',attrs={'class':'section_sub_nav'})
    #h获取各区域
    for item in positionInfo:
         pzzr=item.find_all('a')
         #print(pzzr)
         for item in pzzr:
             link = item.get('class')
             #判断如果是该区则返回
             if link:
                 return item.string
    pass
#判定数字 
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False  
def Crawling_data(url1,regin,regin1):
    #循环抓取列表页信息
    for i in range(1,10):
         if i == 1:
             i=str(i)
             a=(url1+'/'+page+i+'/')
             r=requests.get(url=a,headers=headers)
             html=r.content
         else:
             i=str(i)                
             a=(url1+'/'+page+i+'/')
             r=requests.get(url=a,headers=headers)
             html2=r.content
             html = html + html2
         #每次间隔0.5秒
         time.sleep(0.5)
    #解析抓取的页面内容
    lj=BeautifulSoup(html,'html.parser')
    #提取房源总价
    price=lj.find_all('div',attrs={'class':'priceInfo'})
    tp=[]
    re = []
    for a in price:
        totalPrice=a.span.string
        #print(totalPrice)
        tp.append(totalPrice)
        re.append(regin)
    #提取房源信息
    houseInfo=lj.find_all('div',attrs={'class':'houseInfo'})   
    #hi=[]
    xiaoqu = []
    huxing = []
    mianji = []
    chaoxiang = []
    zhuangxiu = []
    dianti = []
    l = []
    for b in houseInfo:
        house=b.get_text()
        #数据清洗
        l = house.split('/')
        #print(l[1].split('室')[0])
        if len(l)==7:
            del l[1]
        if len(l)==6 and not (is_number(l[1].split('室')[0])):
            del l[1]
        if len(l)==5:
            l.append('无电梯')
        #hi.append(house)
        #print(l)
        xiaoqu.append(l[0])
        huxing.append(l[1])
        mianji.append(float(l[2].split('平米')[0]))
        chaoxiang.append(l[3])
        zhuangxiu.append(l[4])
        dianti.append(l[5])
    #提取房源关注度
    followInfo=lj.find_all('div',attrs={'class':'followInfo'})
    guanzhu=[]
    daikan=[]
    unitprice = []      
    for c in followInfo:
        follow=c.get_text()
        if len(follow.split('/'))!=3:
            print(follow.split('/'))
        #print(len(follow.split('/'))!=3)
        guanzhu.append(int(follow.split('/')[0].split('人关注')[0]))
        daikan.append(int(follow.split('/')[1].split('次带看')[0]))
        #fi.append(follow)
        unitprice.append(int(follow.split('/')[1].split('单价')[1].split('元')[0]))
    #创建数据表
    house=pd.DataFrame({'region':re,'totalprice':tp,'unitprice':unitprice,'xiaoqu':xiaoqu,'huxing':huxing,'mianji':mianji,'chaoxiang':chaoxiang,'zhuangxiu':zhuangxiu,'dianti':dianti,'guanzhu':guanzhu,'daikan':daikan})
    print(len(house))
    if len(house):
#保存数据
        house.to_csv("lianjiawang"+regin1+".csv",encoding="GBK")
    pass
if __name__ == '__main__':
    main()

免费评分

参与人数 2吾爱币 +1 热心值 +2 收起 理由
CalvinMcCain + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
吾爱小洪 + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| zyt温柔发 发表于 2019-6-16 00:03
禁止发春 发表于 2019-6-15 23:30
LZ,可以直接把url改成其他城市的来获取其他城市的二手房数据吗

url改了需要修改代码的,因为不同城市的网站设置的class不一样,所以没什么办法,你可以在我的代码基础上进行修改
禁止发春 发表于 2019-6-18 12:28
zyt温柔发 发表于 2019-6-16 00:03
url改了需要修改代码的,因为不同城市的网站设置的class不一样,所以没什么办法,你可以在我的代码基础上 ...

好的,感谢分享
吾爱小洪 发表于 2019-6-15 22:55
jiang196771 发表于 2019-6-15 23:17
要火呀,哥你厉害
禁止发春 发表于 2019-6-15 23:30
LZ,可以直接把url改成其他城市的来获取其他城市的二手房数据吗
家有皓哥 发表于 2019-6-16 01:44
大哥 源代码可以分享一下么?
zyj66 发表于 2019-6-16 07:15
赞一个,很不错的数据统计。
ALCATEL 发表于 2019-6-16 09:00
哇,这个帖子好
FattyKONG 发表于 2019-6-17 15:15
老哥厉害!!!!!!
时空之外 发表于 2019-6-18 11:13
单变量线性回归?只有面积嘛
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-3-28 19:27

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表