研究组对于集中式公寓项目的数据需求源源不断,这不又需要招商蛇口集中式公寓项目在全国各城市的项目名称,起始租金,总房源数以及详细地址,网上找了半天发现没有官网,于是找呀找,找到了他们的微信公众号“招商公寓”,复制链接地址到浏览器还打不开,提示
只好用微信自带的浏览器打开如下图
分别点击每个城市的页面,右击选择查看源代码(O),自动弹出一个html样式的txt文件,另存为“城市名.txt”,于是有了下面若干个txt文本
有了各个城市的源代码,就相当于有了各个城市所有项目的信息了,现在的问题只要把这些信息解析出来,我们还是用BeautifulSoup这个模块。
# -*- coding: utf-8 -*-
"""
project_name:apartmentone
@author: 帅帅de三叔
Created on Tue Sep 17 14:57:16 2019
"""
import re #导入正则模块
from bs4 import BeautifulSoup #导入网页解析模块
import pymysql #导入数据库模块
db=pymysql.connect("localhost","root","123456","zhaoshangshekou",charset="UTF8MB4") #链接数据库
cursor=db.cursor() #获取操作数据库的游标
cursor.execute("drop table if exists apartmentone") #以重新写入的方式写入数据库
c_sql="""create table apartmentone(
city varchar(8),
project_name varchar(20),
start_price varchar(6),
total_room_num int(4),
address varchar(50))Engine=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=UTF8MB4"""
cursor.execute(c_sql) #创建表apartmentone
files=["南京.txt","漳州.txt","天津.txt","深圳.txt","上海.txt","武汉.txt","重庆.txt"] #构造文件列表
for file in files:
f=open(file,encoding='UTF8') #打开txt文件
str=f.read() #读取文件数据
soup=BeautifulSoup(str,'lxml') #解析数据
city=soup.find("div", class_="city-btn").find("span").get_text() #城市
project_list=soup.find("ul", class_="list").findAll("li") #项目列表
for project in project_list:
project_name=project.find("div", class_="floatL").find("span").get_text().strip() #项目名称
pattern=re.compile("\d+") #正则匹配模式
start_price=re.search(pattern,project.find("span",class_="price").get_text().strip().replace(" ","")).group(0) #起始价格
total_room_num=int(re.search(pattern,project.find("div",class_="floatL").get_text().split("\n")[-4].strip().replace("\t","")).group(0)) #房间总数
address=project.find("div", class_="floatL").get_text().split("\n")[-1].strip().replace("\t","") #详细地址
#print(city,project_name,start_price,total_room_num,address) #测试一下
insert_data=("insert into apartmentone(city,project_name,start_price,total_room_num,address)""values(%s,%s,%s,%s,%s)") #控制插入格式
available_data=([city,project_name,start_price,total_room_num,address]) #待插入数据库数据
cursor.execute(insert_data,available_data) #执行插入操作
db.commit() #主动提交执行
代码解读
首先是构造txt文件列表,然后一个个的读取里面数据形成待解析的内容,在获取项目总房源数和地址的时候,由于缺乏对应标签,所以采用先提取大块内容,然后再拆分形成列表获取对应的字段。
结果截图Python爬虫仅为学习交流,如有冒犯,请告知删。
延申阅读
青客公寓挂牌房源分城市爬取
优客逸家挂牌房源爬取
建方公寓挂牌房源信息爬取
江寓租房挂牌房源信息爬取
通过关键词获取微博内容
家长帮分板块爬取
BIG+碧家国际社区集中式公寓项目爬取