利用python爬取贝壳网租房信息
最近准备换房子,在网站上寻找各种房源信息,看得眼花缭乱,于是想着能否将基本信息汇总起来便于查找,便用python将基本信息爬下来放到excel,这样一来就容易搜索了。
1. 利用lxml中的xpath提取信息
xpath是一门在 xml文档中查找信息的语言,xpath可用来在 xml 文档中对元素和属性进行遍历。对比正则表达式 re两者可以完成同样的工作,实现的功能也差不多,但xpath明显比re具有优势。具有如下优点:(1)可在xml中查找信息 ;(2)支持html的查找;(3)通过元素和属性进行导航
2. 利用xlsxwriter模块将信息保存只excel
xlsxwriter是操作excel的库,可以帮助我们高效快速的,大批量的,自动化的操作excel。它可以写数据,画图,完成大部分常用的excel操作。缺点是xlsxwriter 只能创建新文件,不可以修改原有文件,如果创建新文件时与原有文件同名,则会覆盖原有文件。
3. 爬取思路
观察发现贝壳网租房信息总共是100页,我们可以分每页获取到html代码,然后提取需要的信息保存至字典,将所有页面的信息汇总,最后将字典数据写入excel。
4. 爬虫源代码
# @Author: Rainbowhhy
# @Date : 19-6-25 下午6:35 import requests
import time
from lxml import etree
import xlsxwriter def get_html(page):
"""获取网站html代码"""
url = "https://bj.zu.ke.com/zufang/pg{}/#contentList".format(page)
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
response = requests.get(url, headers=headers).text
return response def parse_html(htmlcode, data):
"""解析html代码"""
content = etree.HTML(htmlcode)
results = content.xpath('///div[@class="content__article"]/div[1]/div')
for result in results[:]:
community = result.xpath('./div[1]/p[@class="content__list--item--title twoline"]/a/text()')[0].replace('\n',
'').strip().split()[
0]
address = "-".join(result.xpath('./div/p[@class="content__list--item--des"]/a/text()'))
landlord = result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')[0].replace('\n',
'').strip() if len(
result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')) > 0 else ""
postime = result.xpath('./div/p[@class="content__list--item--time oneline"]/text()')[0]
introduction = ",".join(result.xpath('./div/p[@class="content__list--item--bottom oneline"]/i/text()'))
price = result.xpath('./div/span/em/text()')[0]
description = "".join(result.xpath('./div/p[2]/text()')).replace('\n', '').replace('-', '').strip().split()
area = description[0]
count = len(description)
if count == 6:
orientation = description[1] + description[2] + description[3] + description[4]
elif count == 5:
orientation = description[1] + description[2] + description[3]
elif count == 4:
orientation = description[1] + description[2]
elif count == 3:
orientation = description[1]
else:
orientation = ""
pattern = description[-1]
floor = "".join(result.xpath('./div/p[2]/span/text()')[1].replace('\n', '').strip().split()).strip() if len(
result.xpath('./div/p[2]/span/text()')) > 1 else ""
date_time = time.strftime("%Y-%m-%d", time.localtime())
"""数据存入字典"""
data_dict = {
"community": community,
"address": address,
"landlord": landlord,
"postime": postime,
"introduction": introduction,
"price": '¥' + price,
"area": area,
"orientation": orientation,
"pattern": pattern,
"floor": floor,
"date_time": date_time
} data.append(data_dict) def excel_storage(response):
"""将字典数据写入excel"""
workbook = xlsxwriter.Workbook('./beikeHouse.xlsx')
worksheet = workbook.add_worksheet()
"""设置标题加粗"""
bold_format = workbook.add_format({'bold': True})
worksheet.write('A1', '小区名称', bold_format)
worksheet.write('B1', '租房地址', bold_format)
worksheet.write('C1', '房屋来源', bold_format)
worksheet.write('D1', '发布时间', bold_format)
worksheet.write('E1', '租房说明', bold_format)
worksheet.write('F1', '房屋价格', bold_format)
worksheet.write('G1', '房屋面积', bold_format)
worksheet.write('H1', '房屋朝向', bold_format)
worksheet.write('I1', '房屋户型', bold_format)
worksheet.write('J1', '房屋楼层', bold_format)
worksheet.write('K1', '查看日期', bold_format) row = 1
col = 0
for item in response:
worksheet.write_string(row, col, item['community'])
worksheet.write_string(row, col + 1, item['address'])
worksheet.write_string(row, col + 2, item['landlord'])
worksheet.write_string(row, col + 3, item['postime'])
worksheet.write_string(row, col + 4, item['introduction'])
worksheet.write_string(row, col + 5, item['price'])
worksheet.write_string(row, col + 6, item['area'])
worksheet.write_string(row, col + 7, item['orientation'])
worksheet.write_string(row, col + 8, item['pattern'])
worksheet.write_string(row, col + 9, item['floor'])
worksheet.write_string(row, col + 10, item['date_time'])
row += 1
workbook.close() def main():
all_datas = []
"""网站总共100页,循环100次"""
for page in range(1, 100):
html = get_html(page)
parse_html(html, all_datas)
excel_storage(all_datas) if __name__ == '__main__':
main()
5. 信息截图

利用python爬取贝壳网租房信息的更多相关文章
- Python 爬取赶集网租房信息
代码已久,有可能需要调整 #coding:utf-8 from bs4 import BeautifulSoup #有这个bs4不用正则也可以定位要爬取的内容了 from urlparse impor ...
- Python爬虫基础--分布式爬取贝壳网房屋信息(Client)
1. client_code01 2. client_code02 3. 这个时候运行多个client就可以分布式进行数据爬取.
- 利用python爬取全国水雨情信息
分析 我们没有找到接口,所以打算利用selenium来爬取. 代码 import datetime import pandas as pd from bs4 import BeautifulSoup ...
- Python爬虫基础--分布式爬取贝壳网房屋信息(Server)
1. server_code01 2. server_code02 3. server_code03
- Python爬虫项目--爬取自如网房源信息
本次爬取自如网房源信息所用到的知识点: 1. requests get请求 2. lxml解析html 3. Xpath 4. MongoDB存储 正文 1.分析目标站点 1. url: http:/ ...
- python爬取当当网的书籍信息并保存到csv文件
python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...
- 利用Selenium爬取淘宝商品信息
一. Selenium和PhantomJS介绍 Selenium是一个用于Web应用程序测试的工具,Selenium直接运行在浏览器中,就像真正的用户在操作一样.由于这个性质,Selenium也是一 ...
- 利用python爬取58同城简历数据
利用python爬取58同城简历数据 利用python爬取58同城简历数据 最近接到一个工作,需要获取58同城上面的简历信息(http://gz.58.com/qzyewu/).最开始想到是用pyth ...
- 利用python爬取城市公交站点
利用python爬取城市公交站点 页面分析 https://guiyang.8684.cn/line1 爬虫 我们利用requests请求,利用BeautifulSoup来解析,获取我们的站点数据.得 ...
随机推荐
- 超详细windows安装mongo数据库、注册为服务并添加环境变量
1.官网下载zip安装包 官网地址https://www.mongodb.com/download-center/community?jmp=nav,现在windows系统一般都是64位的,选好版本. ...
- 3. 懂了这些,方敢在简历上说会用Jackson写JSON
你必须非常努力,才能看起来毫不费力.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免费学习.关注公众 ...
- Python字符串内建函数_上
Python字符串内建函数: 注:汉字属于字符(既是大写又是小写).数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字. 1.capitalize( ): 将字符串第一个字母大 ...
- Python execfile() 函数
描述 execfile() 函数可以用来执行一个文件.每组词 www.cgewang.com 语法 以下是 execfile() 方法的语法: execfile(filename[, globals[ ...
- PHP filegroup() 函数
定义和用法 filegroup() 函数返回指定文件的组 ID. 如果成功,该函数返回指定文件所属组的 ID.如果失败,则返回 FALSE. 语法 filegroup(filename) 参数 描述 ...
- PHP is_dir() 函数
定义和用法 is_dir() 函数检查指定的文件是否是一个目录. 如果目录存在,该函数返回 TRUE. 语法 is_dir(file) 参数 描述 file 必需.规定要检查的文件. 提示和注释 注释 ...
- CF EC 87 div2 1354 C2 Not So Simple Polygon Embedding 计算几何 结论
LINK:Not So Simple Polygon Embedding 搞了好久终于搞会了. 错误原因 没找到合适算边长的方法 要么就是边长算的时候算错了. 几何学的太差了 最后虽然把十边形的和六边 ...
- 牛客练习赛63 C 牛牛的揠苗助长 主席树 二分 中位数
LINK:牛牛的揠苗助长 题目很水 不过做法很多 想到一个近乎O(n)的做法 不过感觉假了 最后决定莽一个主席树 当然 平衡树也行. 容易想到 答案为ans天 那么一些点的有效增长项数为 ans%n. ...
- 【SDOI2012】Longge 的问题 题解(欧拉函数)
前言:还算比较简单的数学题,我这种数学蒟蒻也会做QAQ. --------------- 题意:求$\sum\limits_{i=1}^n gcd(i,n)$的值. 设$gcd(i,n)=d$,即$d ...
- Android线性布局和帧布局
第二次,本牛崽十分从容,今天咱们来讲讲Android Q之布局,我遇到的问题与自己学到的,大牛不要嘲笑哈,有错误可以指出来,本牛崽看到就改了. 今天我的学长跟我们开始了布局,布局看资料说好像有5种,又 ...