打开链家网页:https://sh.lianjia.com/zufang/  :用F12以页面中元素进行检查

<a target="_blank" href="/zufang/pudong/">浦东</a>
<a href="/zufang/jinqiao/" target="_blank">川沙</a>
<a title="园西小区" href="/zufang/c5011000007323/" target="_blank">园西小区</a>

二 解析数据

解析数据是我们首先需要分配一块用于暂存数据的空间datalist ,然后就是对获取到的资源进行解析。这里我们再定义一个 data 用来存储解析出来的数据。我们解析的是HTML格式,所以我们使用的是html.parser,然后使用find_all函数查找符合的字符串,这里我们需要注意的就是要将我们查找的item条目转换成字符串格式,否则无法识别。使用re库通过正则表达式查找到指定的字符串后,运用data.append语句将字符串加入到data中。

三 储存数据

将网页爬的数据储存下来,接着把数据存入excel,定义函数,然后创建workbook对象和工作表,然后在工作表中创建前面爬取的条目,再向表中写入数据即可。

综合代码

import re #正则表达式,进行文字匹配
from bs4 import BeautifulSoup#网页解析,获取数据
import urllib.request,urllib.error #制定URL,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行SQLLite数据库操作# 区域
findplace1 = re.compile(r'<a href="/zufang/.*" target="_blank">(.*)</a>-<a href="/zufang/.* target="_blank">.*</a>-<a href="/zufang.*" target="_blank" title=".*">.*</a>')  # 创建正则表达式对象,表示规则(字符串的模式)findplace2 = re.compile(r'<a href="/zufang/.*" target="_blank">.*</a>-<a href="/zufang/.* target="_blank">(.*)</a>-<a href="/zufang.*" target="_blank" title=".*">.*</a>')findplace3 = re.compile(r'<a href="/zufang/.*" target="_blank">.*</a>-<a href="/zufang/.* target="_blank">.*</a>-<a href="/zufang.*" target="_blank" title=".*">(.*)</a>')
#房子大小
finddaxiao = re.compile(r'<i>/</i>(.*)<i>/</i>.*<i>/</i>.*<span class="hide">',re.S)    #re.s让换行符包含在字符中
#房子朝向
findfangxiang = re.compile(r'<i>/</i>.*<i>/</i>(.*)<i>/</i>.*<span class="hide">',re.S)
#房子规格
findguige = re.compile(r'<i>/</i>.*<i>/</i>.*<i>/</i>(.*)<span class="hide">',re.S)
#楼层类型
findleixing = re.compile(r'<p class="content__list--item--des">.*<i>/</i>(.*)</span>.*</p>.*<p class="content__list--item--bottom oneline">',re.S)
#是否靠近地铁
findsubway = re.compile(r'<i class="content__item__tag--is_subway_house">(.*)</i>')
#是否是精装
finddecoration = re.compile(r'<i class="content__item__tag--decoration">(.*)</i>')
#是否可以随时看房
findkey = re.compile(r'<i class="content__item__tag--is_key">(.*)</i>')
#是否是新上的
findnew = re.compile(r'<i class="content__item__tag--is_new">(.*)</i>')
#维护时间
findtime = re.compile(r'<span class="content__list--item--time oneline">(.*)</span>')
#平均租金
findmoney = re.compile(r'<span class="content__list--item-price"><em>(.*)</em>')
def main():dbpath="fangjia.db"               #用于指定数据库存储路径savepath="fangjia.xls"             #用于指定excel存储路径baseURL="https://sh.lianjia.com/zufang/"  #爬取的网页初始链接dataList=getData(baseURL)saveData(dataList,savepath)saveDataDB(dataList,dbpath)
def askURL(url):head = {  # 模拟浏览器头部信息,向链家服务器发送消息"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"}# 用户代理,表示告诉链家服务器,我们是什么类型的机器,浏览器(本质上是爬虫)request = urllib.request.Request(url, headers=head)html = ""try:response = urllib.request.urlopen(request)html = response.read().decode("utf-8")#print(html)    测试用的except urllib.error.URLError as e:if hasattr(e,"code"):print(e.code)if hasattr(e,"reason"):print(e.reason)return htmldef getData(baseurl):  # 调用获取页面信息的函数datalist = []  # 分配暂存的空间for i in range(0, 100):url = baseurl + str(i)html = askURL(url)  # 保存获取到的网页源码# print(html)    #测试用的代码# 逐一解析数据(边获取边解析)soup = BeautifulSoup(html, "html.parser")  # html.parser是html的解析器for item in soup.find_all('div', class_="content__list--item"):  # 查找符合要求的字符串,形成列表# print(item) #测试:查看链家item全部信息data = []item = str(item)  # 转换成字符串,否则无法识别place1 = re.findall(findplace1, item)[0]  # re库用来通过正则表达式查找指定的字符串place2 = re.findall(findplace2, item)[0]place = place1 + '-' + place2data.append(place)  # 添加地址daxiao = re.findall(finddaxiao, item)[0]daxiao = daxiao.strip()data.append(daxiao.replace("㎡", ""))  # 添加房子大小(平米)并替换前后空格fangxiang = re.findall(findfangxiang, item)[0]data.append(fangxiang.replace(" ", ""))  # 添加房子朝向并替换空格guige = re.findall(findguige, item)[0]data.append(guige.replace(" ", ""))  # 添加房子户型并替换空格leixing1 = re.findall(findleixing, item)[0]leixing2 = leixing1.strip()  # 去掉前后空格leixing3 = leixing2.replace(" ", "")  # 将空格替换掉data.append(leixing3[0:3])  # 添加房子楼层类型并替换空格data.append(leixing3[4:8].replace("层)", ""))  # 添加房子层数并替换掉()subway = re.findall(findsubway, item)  # 可能写有靠近地铁if (len(subway)) != 0:subway = subway[0]data.append(subway)  # 添加近地铁else:data.append("不靠近地铁")  # 添加不靠近地铁decoration = re.findall(finddecoration, item)if len(decoration) != 0:decoration = decoration[0]data.append(decoration)  # 添加精装else:data.append("不是精装")  # 添加不是精装key = re.findall(findkey, item)if len(key) != 0:key = key[0]data.append(key)  # 添加随时看房else:data.append("不是随时看房")  # 添加不是随时看房new = re.findall(findnew, item)if len(new) != 0:new = new[0]data.append(new)  # 添加新上else:data.append("不是新上")  # 添加不是新上time = re.findall(findtime, item)[0]data.append(time)  # 添加维护时间money = re.findall(findmoney, item)[0]data.append(money)  # 添加平均租金(元/月)datalist.append(data)  # 将data中的数据放入datalist中return datalistdef saveData(datalist,savepath):print("save...")book = xlwt.Workbook(encoding="utf-8",style_compression=0)    #创建workbook对象sheet = book.add_sheet('链家租房信息',cell_overwrite_ok=True)     #创建工作表col = ("区域","房子大小","房子朝向","户型","楼层类型","楼层数","是否靠近地铁","是否是精装","是否可以随时看房","是否是新上的","维护时间","平均租金")for i in range(0,12):sheet.write(0,i,col[i]) #列名for i in range(0,3000):print("第%d条" %(i+1))data = datalist[i]for j in range(0,12):sheet.write(i+1,j,data[j])  #数据book.save(savepath)def saveDataDB(datalist, dbpath):init_db(dbpath)conn = sqlite3.connect(dbpath)  # 链接数据库cur = conn.cursor()  # 游标for data in datalist:for index in range(len(data)):if index == 3 or index == 7 or index == 13:  # 遇见numeric类型时不转换成"xx"型continuedata[index] = '"' + data[index] + '"'  # 转换成"xx"型sql = '''insert into homes (info_link,place,xiaoqu,size,chaoxiang,huxing,type,num,subway,decoration,key,new,time,money)values('%s')''' % ",".join(data)cur.execute(sql)  # 执行sql语句conn.commit()  # 提交结果cur.close()  # 关闭游标conn.close()  # 关闭连接print("save....")
def init_db(dbpath):sql = '''create table homes(id integer primary key autoincrement,info_link text,place text,xiaoqu text,size numeric,chaoxiang varchar,huxing text,type text,num numeric,subway text,decoration text,key text,new text,time text,money numeric)'''    #创建数据表conn = sqlite3.connect(dbpath)cursor = conn.cursor()cursor.execute(sql)conn.commit()conn.close()
if __name__=="__main__":    #程序执行入口main()

python爬虫爬取链家网房价信息相关推荐

  1. python+selenium爬取链家网房源信息并保存至csv

    python+selenium爬取链家网房源信息并保存至csv 抓取的信息有:房源', '详细信息', '价格','楼层', '有无电梯 import csv from selenium import ...

  2. python爬取南京市房价_Python的scrapy之爬取链家网房价信息并保存到本地

    因为有在北京租房的打算,于是上网浏览了一下链家网站的房价,想将他们爬取下来,并保存到本地. 先看链家网的源码..房价信息 都保存在 ul 下的li 里面 ​ 爬虫结构: ​ 其中封装了一个数据库处理模 ...

  3. python爬取链家房价消息_Python的scrapy之爬取链家网房价信息并保存到本地

    因为有在北京租房的打算,于是上网浏览了一下链家网站的房价,想将他们爬取下来,并保存到本地. 先看链家网的源码..房价信息 都保存在 ul 下的li 里面 ​ 爬虫结构: ​ 其中封装了一个数据库处理模 ...

  4. 基于python多线程和Scrapy爬取链家网房价成交信息

    文章目录 知识背景 Scrapy- spider 爬虫框架 SQLite数据库 python多线程 爬取流程详解 爬取房价信息 封装数据库类,方便多线程操作 数据库插入操作 构建爬虫爬取数据 基于百度 ...

  5. Python爬虫爬取链家网上的房源信息练习

    一 原链接:用Python爬虫爬取链家网上的房源信息_shayebuhui_a的博客-CSDN博客_python爬取链家 打开链家网页:https://sh.lianjia.com/zufang/  ...

  6. Python爬虫攻略(2)Selenium+多线程爬取链家网二手房信息

    申明:本文对爬取的数据仅做学习使用,请勿使用爬取的数据做任何商业活动,侵删 前戏 安装Selenium: pip install selenium 如果下载速度较慢, 推荐使用国内源: pip ins ...

  7. python爬虫--爬取链家租房信息

    python 爬虫-链家租房信息 爬虫,其实就是爬取web页面上的信息. 链家租房信息页面如下: https://gz.lianjia.com/zufang/ ## python库 Python库 1 ...

  8. python爬虫代码房-python爬虫爬取链家二手房信息

    #coding=utf-8 import requests from fake_useragent import UserAgent from bs4 import BeautifulSoup imp ...

  9. 使用python爬虫爬取卷皮网背包信息实例

    使用requests和BeautifulSoup实现对卷皮网背包名称与价格的爬取 链接:www.juanpi.com 代码: import requests import re from bs4 im ...

最新文章

  1. 利用php和ajax实现的,利用PHP和AJAX实现数据库增值
  2. Redisson官方文档 - 目录
  3. 爬取豆瓣top250的代码
  4. SAP Table 汇总版
  5. MATLAB数字图像处理实验题目要求
  6. 变速齿轮”再研究-----(转帖)
  7. iPhone所有手机型号屏幕尺寸及H5的CSS适配
  8. python数据分析培训南京_基于Python的南京二手房数据可视化分析
  9. Spring 注解@Value详解
  10. 基础设施即代码(IAC),Zalando Postgres Operator 简介
  11. 达梦数据库更换key文件的方法
  12. AndroidManifest--详细理解
  13. 华为机试真题 C++ 实现【模拟商场优惠打折】【2022.11 Q4 新题】
  14. DataStage问题汇总
  15. PostgreSQL登录及修改密码
  16. 如何通过6个简单步骤让百度收录你的网站
  17. javascript学习笔记下篇--浏览器对象
  18. 文思海辉bg1到bg7_BG的完整形式是什么?
  19. 上古卷轴5mo未安装python_勇敢的罗宾爵士 - Monty Python Mod
  20. java 2022-09-21T10:41:00.000+0800 转换成 yyyy-MM-dd HH:mm:ss

热门文章

  1. RabbitMQ常见问题解决方案——消息丢失、重复消费、消费乱序、消息积压
  2. siri买的微软的服务器,微软要抢Siri饭碗:开始公开测试iOS版Cortana
  3. 网络:抓包分析ping的原理
  4. kafka中kafkaConsumer的poll拉取方法
  5. performSelector等使用总结
  6. Bugku CTF每日一题 可爱的故事
  7. C++多线程以及线程池
  8. 计算机bootmgr丢失,电脑开机提示bootmgr is missing的解决方法
  9. 华为笔试:字符串加密(python版)
  10. 微信小程序--实时语音识别