1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # @Time : 2019-08-16 15:56
4 # @Author : Anthony
5 # @Email : ianghont7@163.com
6 # @File : 爬取链家任意城市租房数据.py
7
8
9 import requests
10 from lxml import etree
11 import time
12 import xlrd
13 import os
14 import xlwt
15 from xlutils.copy import copy
16
17 # 伪装请求
18 headers = {
19 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.7 Safari/537.36'
20 }
21
22 xlsInfo = {}
23
24 def catchHouseDetail(url):
25 # 通过requests模块模拟get请求
26 page_text = requests.get(url, headers=headers, stream=True)
27
28 # 将互联网上获取的页面数据加载到etree对象中
29 tree = etree.HTML(page_text.text)
30
31 # 定位页面标签位置装入一个list中
32 li_list = tree.xpath('//div[@class="content w1150"]/div[@class="content__article"]/div[@class="content__list"]/div')
33 all_house_list = []
34 # 遍历列表中每一个字段
35 for li in li_list:
36 info = []
37 # 房屋标题
38 # houseTitles = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--bottom oneline"]/i/text()')
39 # print(*houseTitles)
40 # 租房方式
41 houseWay = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--title twoline"]/a/text()')[0].strip().split(' ')[0].split('·')[0]
42 # 月租金额
43 houseMoney = li.xpath('.//div[@class="content__list--item--main"]/span[@class="content__list--item-price"]/em/text()')[0]+'元/月'
44 # 小区名称
45 plotName = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--title twoline"]/a/text()')[0].strip().split(' ')[0].split('·')[1]
46 # 房屋大小
47 houseSize = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--des"]/text()')[4].strip()
48 # 房屋户型
49 houseType = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--title twoline"]/a/text()')[0].strip().split(' ')[1]
50 # 房屋朝向
51 houseOrientation = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--title twoline"]/a/text()')[0].strip().split(' ')[2]
52 # 区域位置
53 communityArea = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--des"]/a/text()')[0]
54 # 地铁站名称
55 subwayArea = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--des"]/a/text()')[1]
56 # 小区名称
57 # plotName = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--des"]/a/text()')[2]
58 # 发布时间
59 releaseTime = li.xpath('.//div[@class="content__list--item--main"]/p[@class="content__list--item--time oneline"]/text()')[0]
60
61 info.append(houseWay)
62 info.append(houseMoney)
63 info.append(plotName)
64 info.append(houseSize)
65 info.append(houseType)
66 info.append(houseOrientation)
67 info.append(communityArea)
68 info.append(subwayArea)
69 info.append(releaseTime)
70
71 all_house_list.append(info)
72 if if_xls_exits() == True:
73 write_excel_xls_append(xlsInfo["xlsName"],all_house_list)
74
75 # print(catchHouseDetail('https://bj.lianjia.com/zufang/chaoyang/pg1'))
76
77
78 #获取数据写入xls表格中
79 def write_excel_xls(path, sheet_name, value):
80 index = len(value) # 获取需要写入数据的行数
81 workbook = xlwt.Workbook() # 新建一个工作簿
82 sheet = workbook.add_sheet(sheet_name) # 在工作簿中新建一个表格
83 for i in range(0, index):
84 for j in range(0, len(value[i])):
85 sheet.write(i, j, value[i][j]) # 像表格中写入数据(对应的行和列)
86 workbook.save(path) # 保存工作簿
87 print("xls格式表格写入数据成功!")
88
89
90
91 def write_excel_xls_append(path, value):
92 index = len(value) # 获取需要写入数据的行数
93 workbook = xlrd.open_workbook(path) # 打开工作簿
94 sheets = workbook.sheet_names() # 获取工作簿中的所有表格
95 worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格
96 rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
97 new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
98 new_worksheet = new_workbook.get_sheet(0) # 获取转化后工作簿中的第一个表格
99 for i in range(0, index):
100 for j in range(0, len(value[i])):
101 new_worksheet.write(i + rows_old, j, value[i][j]) # 追加写入数据,注意是从i+rows_old行开始写入
102 new_workbook.save(path) # 保存工作簿
103 print("xls格式表格【追加】写入数据成功!")
104
105
106
107
108 def if_xls_exits():
109 while True:
110 book_name_xls = '北京链家租房信息表.xls'
111 sheet_name_xls = '房屋信息'
112 value_title = [["租房方式", "月租金额", "小区名称", "房屋大小", "房屋户型", "房屋朝向", "区域位置", "地铁站名称", "房屋发布时间"], ]
113 if os.path.exists('./%s'%book_name_xls):
114 xlsInfo["xlsName"] = book_name_xls
115 return True
116 else:
117 write_excel_xls(book_name_xls, sheet_name_xls, value_title)
118 continue
119
120
121
122
123
124 def catch():
125 pages = ['https://bj.lianjia.com/zufang/chaoyang/pg{}/'.format(x) for x in range(1,100)]
126 for page in pages:
127 try:
128 info = catchHouseDetail(page)
129 except:
130 pass
131 time.sleep(2)
132
133
134 if __name__ == '__main__':
135 catch()
效果图:
![](https://img2018.cnblogs.com/blog/1394549/201908/1394549-20190816193410882-4149538.png)