最近准备换房子,在网站上寻找各种房源信息,看得眼花缭乱,于是想着能否将基本信息汇总起来便于查找,便用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. 爬虫源代码

  1. # @Author: Rainbowhhy
  2. # @Date : 19-6-25 下午6:35
  3.  
  4. import requests
  5. import time
  6. from lxml import etree
  7. import xlsxwriter
  8.  
  9. def get_html(page):
  10. """获取网站html代码"""
  11. url = "https://bj.zu.ke.com/zufang/pg{}/#contentList".format(page)
  12. headers = {
  13. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
  14. }
  15. response = requests.get(url, headers=headers).text
  16. return response
  17.  
  18. def parse_html(htmlcode, data):
  19. """解析html代码"""
  20. content = etree.HTML(htmlcode)
  21. results = content.xpath('///div[@class="content__article"]/div[1]/div')
  22. for result in results[:]:
  23. community = result.xpath('./div[1]/p[@class="content__list--item--title twoline"]/a/text()')[0].replace('\n',
  24. '').strip().split()[
  25. 0]
  26. address = "-".join(result.xpath('./div/p[@class="content__list--item--des"]/a/text()'))
  27. landlord = result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')[0].replace('\n',
  28. '').strip() if len(
  29. result.xpath('./div/p[@class="content__list--item--brand oneline"]/text()')) > 0 else ""
  30. postime = result.xpath('./div/p[@class="content__list--item--time oneline"]/text()')[0]
  31. introduction = ",".join(result.xpath('./div/p[@class="content__list--item--bottom oneline"]/i/text()'))
  32. price = result.xpath('./div/span/em/text()')[0]
  33. description = "".join(result.xpath('./div/p[2]/text()')).replace('\n', '').replace('-', '').strip().split()
  34. area = description[0]
  35. count = len(description)
  36. if count == 6:
  37. orientation = description[1] + description[2] + description[3] + description[4]
  38. elif count == 5:
  39. orientation = description[1] + description[2] + description[3]
  40. elif count == 4:
  41. orientation = description[1] + description[2]
  42. elif count == 3:
  43. orientation = description[1]
  44. else:
  45. orientation = ""
  46. pattern = description[-1]
  47. floor = "".join(result.xpath('./div/p[2]/span/text()')[1].replace('\n', '').strip().split()).strip() if len(
  48. result.xpath('./div/p[2]/span/text()')) > 1 else ""
  49. date_time = time.strftime("%Y-%m-%d", time.localtime())
  50. """数据存入字典"""
  51. data_dict = {
  52. "community": community,
  53. "address": address,
  54. "landlord": landlord,
  55. "postime": postime,
  56. "introduction": introduction,
  57. "price": '¥' + price,
  58. "area": area,
  59. "orientation": orientation,
  60. "pattern": pattern,
  61. "floor": floor,
  62. "date_time": date_time
  63. }
  64.  
  65. data.append(data_dict)
  66.  
  67. def excel_storage(response):
  68. """将字典数据写入excel"""
  69. workbook = xlsxwriter.Workbook('./beikeHouse.xlsx')
  70. worksheet = workbook.add_worksheet()
  71. """设置标题加粗"""
  72. bold_format = workbook.add_format({'bold': True})
  73. worksheet.write('A1', '小区名称', bold_format)
  74. worksheet.write('B1', '租房地址', bold_format)
  75. worksheet.write('C1', '房屋来源', bold_format)
  76. worksheet.write('D1', '发布时间', bold_format)
  77. worksheet.write('E1', '租房说明', bold_format)
  78. worksheet.write('F1', '房屋价格', bold_format)
  79. worksheet.write('G1', '房屋面积', bold_format)
  80. worksheet.write('H1', '房屋朝向', bold_format)
  81. worksheet.write('I1', '房屋户型', bold_format)
  82. worksheet.write('J1', '房屋楼层', bold_format)
  83. worksheet.write('K1', '查看日期', bold_format)
  84.  
  85. row = 1
  86. col = 0
  87. for item in response:
  88. worksheet.write_string(row, col, item['community'])
  89. worksheet.write_string(row, col + 1, item['address'])
  90. worksheet.write_string(row, col + 2, item['landlord'])
  91. worksheet.write_string(row, col + 3, item['postime'])
  92. worksheet.write_string(row, col + 4, item['introduction'])
  93. worksheet.write_string(row, col + 5, item['price'])
  94. worksheet.write_string(row, col + 6, item['area'])
  95. worksheet.write_string(row, col + 7, item['orientation'])
  96. worksheet.write_string(row, col + 8, item['pattern'])
  97. worksheet.write_string(row, col + 9, item['floor'])
  98. worksheet.write_string(row, col + 10, item['date_time'])
  99. row += 1
  100. workbook.close()
  101.  
  102. def main():
  103. all_datas = []
  104. """网站总共100页,循环100次"""
  105. for page in range(1, 100):
  106. html = get_html(page)
  107. parse_html(html, all_datas)
  108. excel_storage(all_datas)
  109.  
  110. if __name__ == '__main__':
  111. main()

5. 信息截图

利用python爬取贝壳网租房信息的更多相关文章

  1. Python 爬取赶集网租房信息

    代码已久,有可能需要调整 #coding:utf-8 from bs4 import BeautifulSoup #有这个bs4不用正则也可以定位要爬取的内容了 from urlparse impor ...

  2. Python爬虫基础--分布式爬取贝壳网房屋信息(Client)

    1. client_code01 2. client_code02 3. 这个时候运行多个client就可以分布式进行数据爬取.

  3. 利用python爬取全国水雨情信息

    分析 我们没有找到接口,所以打算利用selenium来爬取. 代码 import datetime import pandas as pd from bs4 import BeautifulSoup ...

  4. Python爬虫基础--分布式爬取贝壳网房屋信息(Server)

    1. server_code01 2. server_code02 3. server_code03

  5. Python爬虫项目--爬取自如网房源信息

    本次爬取自如网房源信息所用到的知识点: 1. requests get请求 2. lxml解析html 3. Xpath 4. MongoDB存储 正文 1.分析目标站点 1. url: http:/ ...

  6. python爬取当当网的书籍信息并保存到csv文件

    python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...

  7. 利用Selenium爬取淘宝商品信息

    一.  Selenium和PhantomJS介绍 Selenium是一个用于Web应用程序测试的工具,Selenium直接运行在浏览器中,就像真正的用户在操作一样.由于这个性质,Selenium也是一 ...

  8. 利用python爬取58同城简历数据

    利用python爬取58同城简历数据 利用python爬取58同城简历数据 最近接到一个工作,需要获取58同城上面的简历信息(http://gz.58.com/qzyewu/).最开始想到是用pyth ...

  9. 利用python爬取城市公交站点

    利用python爬取城市公交站点 页面分析 https://guiyang.8684.cn/line1 爬虫 我们利用requests请求,利用BeautifulSoup来解析,获取我们的站点数据.得 ...

随机推荐

  1. Spring Data R2DBC响应式操作MySQL

    1. 前言 在使用R2DBC操作MySQL数据库 一文中初步介绍了r2dbc-mysql的使用.由于借助DatabaseClient操作MySQL,过于初级和底层,不利于开发.今天就利用Spring ...

  2. zookeeper 源码编译

    环境:mac 1.github上下载 源码 项目地址:https://github.com/apache/zookeeper 2.安装 ant mac:brew update ->  brew ...

  3. Django学习路27_HTML转义

    谨慎使用 自动渲染语法 {{code|safe}} urls.py 中添加对应的函数 url(r'getcode',views.getcode) 在 views.py 中添加 def getcode( ...

  4. python基础day5_元组

    元祖---只读列表,可循环查询,可切片 儿子不能改,孙子可能可以改.增加(主要看要操作的是属于列表还是元组) tu = (1,2,3,'alex',[2,3,4,'taibai'],'egon') t ...

  5. Python List insert()方法

    描述 insert() 函数用于将指定对象插入列表的指定位置.高佣联盟 www.cgewang.com 语法 insert()方法语法: list.insert(index, obj) 参数 inde ...

  6. luogu 1587 [NOI2016]循环之美

    LINK:NOI2016循环之美 这道题是 给出n m k 求出\(1\leq i\leq n,1\leq j\leq m\) \(\frac{i}{j}\)在k进制下是一个纯循环的. 由于数值相同的 ...

  7. P3250 [HNOI2016]网络

    LINK:网络 一棵树 每次添加一条路径 或者删除之前的一条路径 或询问除了不经过某个点之外剩下的最大值. 一个显然的思路 对于一条路径的权值我们直接把权值塞上去 标记永久化一下即可. 考虑如何求答案 ...

  8. RabbitMQ学习总结(1)-基础概念

    1. 概念 1.1 AMQP协议 AMQP,即Advanced Message Queuing Protocol,一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消 ...

  9. VulnHub靶场学习_HA: Natraj

    HA: Natraj Vulnhub靶场 下载地址:https://www.vulnhub.com/entry/ha-natraj,489/ 背景: Nataraj is a dancing avat ...

  10. 文件权限和访问控制列表ACL (1)

    背景知识: 文件的权限主要针对三类对象进行定义 Owner: 属主u Group: 属组g Other: 其他o 每个文件针对每一类的访问者都设定了三种权限 r: Readable 读 w: Writ ...