Python爬虫入门案例之爬取二手房源数据

本文重点

  • 系统分析网页性质
  • 结构化的数据解析
  • csv数据保存

环境介绍

  • python 3.8
  • pycharm 专业版 >>> 激活码

#模块使用

  • requests >>> pip install requests
  • parsel >>> pip install parsel
  • csv

【付费VIP完整版】只要看了就能学会的教程,80集Python基础入门视频教学

点这里即可免费在线观看

爬虫代码实现步骤: 发送请求 >>> 获取数据 >>> 解析数据 >>> 保存数据

导入模块

import requests # 数据请求模块 第三方模块 pip install requests
import parsel # 数据解析模块
import re
import csv

发送请求, 对于房源列表页发送请求

url = 'https://bj.lianjia.com/ershoufang/pg1/'
# 需要携带上 请求头: 把python代码伪装成浏览器 对于服务器发送请求
# User-Agent 浏览器的基本信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
}
response = requests.get(url=url, headers=headers)

获取数据

print(response.text)

解析数据

selector_1 = parsel.Selector(response.text)
# 把获取到response.text 数据内容转成 selector 对象
href = selector_1.css('div.leftContent li div.title a::attr(href)').getall()
for link in href:
    html_data = requests.get(url=link, headers=headers).text
    selector = parsel.Selector(html_data)
    # css选择器 语法
    # try:
    title = selector.css('.title h1::text').get() # 标题
    area = selector.css('.areaName .info a:nth-child(1)::text').get()  # 区域
    community_name = selector.css('.communityName .info::text').get()  # 小区
    room = selector.css('.room .mainInfo::text').get()  # 户型
    room_type = selector.css('.type .mainInfo::text').get()  # 朝向
    height = selector.css('.room .subInfo::text').get().split('/')[-1]  # 楼层
    # 中楼层/共5层 split('/') 进行字符串分割  ['中楼层', '共5层'] [-1]
    # ['中楼层', '共5层'][-1] 列表索引位置取值 取列表中最后一个元素  共5层
    # re.findall('共(\d+)层', 共5层) >>>  [5][0] >>> 5
    height = re.findall('共(\d+)层', height)[0]
    sub_info = selector.css('.type .subInfo::text').get().split('/')[-1]  # 装修
    Elevator = selector.css('.content li:nth-child(12)::text').get()  # 电梯
    # if Elevator == '暂无数据电梯' or Elevator == None:
    #     Elevator = '无电梯'
    house_area = selector.css('.content li:nth-child(3)::text').get().replace('㎡', '')  # 面积
    price = selector.css('.price .total::text').get()  # 价格(万元)
    date = selector.css('.area .subInfo::text').get().replace('年建', '')  # 年份
    dit = {
        '标题': title,
        '市区': area,
        '小区': community_name,
        '户型': room,
        '朝向': room_type,
        '楼层': height,
        '装修情况': sub_info,
        '电梯': Elevator,
        '面积(㎡)': house_area,
        '价格(万元)': price,
        '年份': date,
    }
    csv_writer.writerow(dit)
    print(title, area, community_name, room, room_type, height, sub_info, Elevator, house_area, price, date,
          sep='|')

保存数据

f = open('二手房数据.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=[
    '标题',
    '市区',
    '小区',
    '户型',
    '朝向',
    '楼层',
    '装修情况',
    '电梯',
    '面积(㎡)',
    '价格(万元)',
    '年份',
])
csv_writer.writeheader()

数据可视化

导入所需模块

import pandas as pd
from pyecharts.charts import Map
from pyecharts.charts import Bar
from pyecharts.charts import Line
from pyecharts.charts import Grid
from pyecharts.charts import Pie
from pyecharts.charts import Scatter
from pyecharts import options as opts

读取数据

df = pd.read_csv('链家.csv', encoding = 'utf-8')
df.head()

各城区二手房数量北京市地图

new = [x + '区' for x in region]
m = (
        Map()
        .add('', [list(z) for z in zip(new, count)], '北京')
        .set_global_opts(
            title_opts=opts.TitleOpts(title='北京市二手房各区分布'),
            visualmap_opts=opts.VisualMapOpts(max_=3000),
        )
    )
m.render_notebook()

各城区二手房数量-平均价格柱状图

df_price.values.tolist()
price = [round(x,2) for x in df_price.values.tolist()]
bar = (
    Bar()
    .add_xaxis(region)
    .add_yaxis('数量', count,
              label_opts=opts.LabelOpts(is_show=True))
    .extend_axis(
        yaxis=opts.AxisOpts(
            name="价格(万元)",
            type_="value",
            min_=200,
            max_=900,
            interval=100,
            axislabel_opts=opts.LabelOpts(formatter="{value}"),
        )
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title='各城区二手房数量-平均价格柱状图'),
        tooltip_opts=opts.TooltipOpts(
            is_show=True, trigger="axis", axis_pointer_type="cross"
        ),
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
        ),
        yaxis_opts=opts.AxisOpts(name='数量',
            axistick_opts=opts.AxisTickOpts(is_show=True),
            splitline_opts=opts.SplitLineOpts(is_show=False),)
    )
)

line2 = (
    Line()
    .add_xaxis(xaxis_data=region)
    .add_yaxis(

        series_name="价格",
        yaxis_index=1,
        y_axis=price,
        label_opts=opts.LabelOpts(is_show=True),
        z=10
        )
)

bar.overlap(line2)
grid = Grid()
grid.add(bar, opts.GridOpts(pos_left="5%", pos_right="20%"), is_control_axis_index=True)
grid.render_notebook()

area0 = top_price['小区'].values.tolist()
count = top_price['价格(万元)'].values.tolist()

bar = (
    Bar()
    .add_xaxis(area0)
    .add_yaxis('数量', count,category_gap = '50%')
    .set_global_opts(
        yaxis_opts=opts.AxisOpts(name='价格(万元)'),
        xaxis_opts=opts.AxisOpts(name='数量'),
    )
)
bar.render_notebook()

散点图

s = (
    Scatter()
    .add_xaxis(df['面积(㎡)'].values.tolist())
    .add_yaxis('',df['价格(万元)'].values.tolist())
    .set_global_opts(xaxis_opts=opts.AxisOpts(type_='value'))
)
s.render_notebook()

房屋朝向占比

directions = df_direction.index.tolist()
count = df_direction.values.tolist()

c1 = (
    Pie(init_opts=opts.InitOpts(
            width='800px', height='600px',
            )
       )
        .add(
        '',
        [list(z) for z in zip(directions, count)],
        radius=['20%', '60%'],
        center=['40%', '50%'],
#         rosetype="radius",
        label_opts=opts.LabelOpts(is_show=True),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title='房屋朝向占比',pos_left='33%',pos_top="5%"),
                        legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%",pos_top="25%",orient="vertical")
                        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter='{b}:{c} ({d}%)'),position="outside")
    )
c1.render_notebook()

装修情况/有无电梯玫瑰图(组合图)

fitment = df_fitment.index.tolist()
count1 = df_fitment.values.tolist()

directions = df_direction.index.tolist()
count2 = df_direction.values.tolist()

bar = (
    Bar()
    .add_xaxis(fitment)
    .add_yaxis('', count1, category_gap = '50%')
    .reversal_axis()
    .set_series_opts(label_opts=opts.LabelOpts(position='right'))
    .set_global_opts(
        xaxis_opts=opts.AxisOpts(name='数量'),
        title_opts=opts.TitleOpts(title='装修情况/有无电梯玫瑰图(组合图)',pos_left='33%',pos_top="5%"),
        legend_opts=opts.LegendOpts(type_="scroll", pos_left="90%",pos_top="58%",orient="vertical")
    )
)

c2 = (
    Pie(init_opts=opts.InitOpts(
            width='800px', height='600px',
            )
       )
        .add(
        '',
        [list(z) for z in zip(directions, count2)],
        radius=['10%', '30%'],
        center=['75%', '65%'],
        rosetype="radius",
        label_opts=opts.LabelOpts(is_show=True),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title='有/无电梯',pos_left='33%',pos_top="5%"),
                        legend_opts=opts.LegendOpts(type_="scroll", pos_left="90%",pos_top="15%",orient="vertical")
                        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter='{b}:{c} \n ({d}%)'),position="outside")
    )

bar.overlap(c2)
bar.render_notebook()

二手房楼层分布柱状缩放图

floor = df_floor.index.tolist()
count = df_floor.values.tolist()
bar = (
    Bar()
    .add_xaxis(floor)
    .add_yaxis('数量', count)
    .set_global_opts(
        title_opts=opts.TitleOpts(title='二手房楼层分布柱状缩放图'),
        yaxis_opts=opts.AxisOpts(name='数量'),
        xaxis_opts=opts.AxisOpts(name='楼层'),
        datazoom_opts=opts.DataZoomOpts(type_='slider')
    )
)
bar.render_notebook()

房屋面积分布纵向柱状图

area = df_area.index.tolist()
count = df_area.values.tolist()

bar = (
    Bar()
    .add_xaxis(area)
    .add_yaxis('数量', count)
    .reversal_axis()
    .set_series_opts(label_opts=opts.LabelOpts(position="right"))
    .set_global_opts(
        title_opts=opts.TitleOpts(title='房屋面积分布纵向柱状图'),
        yaxis_opts=opts.AxisOpts(name='面积(㎡)'),
        xaxis_opts=opts.AxisOpts(name='数量'),
    )
)
bar.render_notebook()

到此这篇关于Python爬虫入门案例之爬取二手房源数据的文章就介绍到这了,更多相关Python 爬取二手房数据内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python爬虫入门案例之回车桌面壁纸网美女图片采集

    目录 知识点 环境 目标网址: 爬虫代码 导入模块 发送网络请求 获取网页源代码 提取每个相册的详情页链接地址 替换所有的图片链接 换成大图 保存图片 图片名字 翻页 爬取结果 知识点 requests parsel re os 环境 python3.8 pycharm2021 目标网址: https://mm.enterdesk.com/bizhi/63899-347866.html [付费VIP完整版]只要看了就能学会的教程,80集Python基础入门视频教学 点这里即可免费在线观看 注意:

  • Python爬虫实战之批量下载快手平台视频数据

    知识点 requests json re pprint 开发环境: 版 本:anaconda5.2.0(python3.6.5) 编辑器:pycharm 案例实现步骤: 一. 数据来源分析 (只有当你找到数据来源的时候, 才能通过代码实现) 1.确定需求 (要爬取的内容是什么?) 爬取某个关键词对应的视频 保存mp4 2.通过开发者工具进行抓包分析 分析数据从哪里来的(找出真正的数据来源)? 静态加载页面 笔趣阁为例 动态加载页面 开发者工具抓数据包 [付费VIP完整版]只要看了就能学会的教程,

  • Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

    目录 知识点 第三方库 开发环境: 爬虫程序 导入模块 发送请求 获取数据(网页源代码) 解析网页(re正则表达式,css选择器,xpath,bs4/六年没更新了,json) 向详情页网站发送请求(get,post) 解析网页 保存数据 数据可视化 导入模块 导入数据 旅游胜地Top10及对应费用 出游方式分析 出游时间分析 出游玩法分析 知识点 requests 发送网络请求 parsel 解析数据 csv 保存数据 第三方库 requests >>> pip install requ

  • Python爬虫实战之用selenium爬取某旅游网站

    一.selenium实战 这里我们只会用到很少的selenium语法,我这里就不补充别的用法了,以实战为目的 二.打开艺龙网 可以直接点击这里进入:艺龙网 这里是主页 三.精确目标 我们的目标是,鹤壁市,所以我们应该先点击搜索框,然后把北京删掉,替换成鹤壁市,那么怎么通过selenium实现呢? 打开pycharm,新建一个叫做艺龙网的py文件,先导包: from selenium import webdriver import time # 导包 driver = webdriver.Chro

  • 详解Python 爬取13个旅游城市,告诉你五一大家最爱去哪玩?

    今年五一放了四天假,很多人不再只是选择周边游,因为时间充裕,选择了稍微远一点的景区,甚至出国游.各个景点成了人山人海,拥挤的人群,甚至去卫生间都要排队半天,那一刻我突然有点理解灭霸的行为了. 今天通过分析去哪儿网部分城市门票售卖情况,简单的分析一下哪些景点比较受欢迎,等下次假期可以做个参考. 抓取数据 通过请求https://piao.qunar.com/ticket/list.htm?keyword=北京,获取北京地区热门景区信息,再通过BeautifulSoup去分析提取出我们需要的信息.

  • Python爬虫入门案例之爬取二手房源数据

    本文重点 系统分析网页性质 结构化的数据解析 csv数据保存 环境介绍 python 3.8 pycharm 专业版 >>> 激活码 #模块使用 requests >>> pip install requests parsel >>> pip install parsel csv [付费VIP完整版]只要看了就能学会的教程,80集Python基础入门视频教学 点这里即可免费在线观看 爬虫代码实现步骤: 发送请求 >>> 获取数据 &g

  • Python爬虫实战案例之爬取喜马拉雅音频数据详解

    前言 喜马拉雅是专业的音频分享平台,汇集了有声小说,有声读物,有声书,FM电台,儿童睡前故事,相声小品,鬼故事等数亿条音频,我最喜欢听民间故事和德云社相声集,你呢? 今天带大家爬取喜马拉雅音频数据,一起期待吧!! 这个案例的视频地址在这里 https://v.douyu.com/show/a2JEMJj3e3mMNxml 项目目标 爬取喜马拉雅音频数据 受害者地址 https://www.ximalaya.com/ 本文知识点: 1.系统分析网页性质 2.多层数据解析 3.海量音频数据保存 环境

  • Python爬虫实现使用beautifulSoup4爬取名言网功能案例

    本文实例讲述了Python爬虫实现使用beautifulSoup4爬取名言网功能.分享给大家供大家参考,具体如下: 爬取名言网top10标签对应的名言,并存储到mysql中,字段(名言,作者,标签) #! /usr/bin/python3 # -*- coding:utf-8 -*- from urllib.request import urlopen as open from bs4 import BeautifulSoup import re import pymysql def find_

  • Python爬虫实现简单的爬取有道翻译功能示例

    本文实例讲述了Python爬虫实现简单的爬取有道翻译功能.分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 import urllib.request import urllib.parse import json while True : content = input("请输入需要翻译的内容:(按q退出)") if content == 'q' : break url = 'http://fanyi.youdao.com/trans

  • Python爬虫小练习之爬取并分析腾讯视频m3u8格式

    目录 普通爬虫正常流程: 环境介绍 分析网站 开始代码 导入模块 数据请求 提取数据 遍历 保存数据 运行代码 普通爬虫正常流程: 数据来源分析 发送请求 获取数据 解析数据 保存数据 环境介绍 python 3.8 pycharm 2021专业版 [付费VIP完整版]只要看了就能学会的教程,80集Python基础入门视频教学 点这里即可免费在线观看 分析网站 先打开开发者工具,然后搜索m3u8,会返回给你很多的ts的文件,像这种ts文件,就是视频的片段 我们可以复制url地址,在新的浏览页打开

  • python爬虫系列Selenium定向爬取虎扑篮球图片详解

    前言: 作为一名从小就看篮球的球迷,会经常逛虎扑篮球及湿乎乎等论坛,在论坛里面会存在很多精美图片,包括NBA球队.CBA明星.花边新闻.球鞋美女等等,如果一张张右键另存为的话真是手都点疼了.作为程序员还是写个程序来进行吧! 所以我通过Python+Selenium+正则表达式+urllib2进行海量图片爬取. 运行效果: http://photo.hupu.com/nba/tag/马刺 http://photo.hupu.com/nba/tag/陈露 源代码: # -*- coding: utf

  • 使用python爬虫实现网络股票信息爬取的demo

    实例如下所示: import requests from bs4 import BeautifulSoup import traceback import re def getHTMLText(url): try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" def getStockList(lst, stockUR

  • Python爬虫实例——scrapy框架爬取拉勾网招聘信息

    本文实例为爬取拉勾网上的python相关的职位信息, 这些信息在职位详情页上, 如职位名, 薪资, 公司名等等. 分析思路 分析查询结果页 在拉勾网搜索框中搜索'python'关键字, 在浏览器地址栏可以看到搜索结果页的url为: 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=', 尝试将?后的参数删除, 发现访问结果相同. 打开Chrome网页调试工具(F12), 分析每条搜索结果

随机推荐