上次获取了链家658家的郑州二手房信息的房源,本次获取的为9600多家的房源信息,共一百页,但由于太多,所以就获取了前50页的内容。获取的速度也是非常的快。
代码如下:
'''
多线程爬取链家二手房信息
'''
# 导入第三方库
import time
import requests
import threading
from lxml import etree
from fake_useragent import UserAgent
from queue import Queue
# 随机请求头
ua = UserAgent()
# 定义多线程爬取链家的类
class LianJiaDuo():
# 初始化对象
def __init__(self):
# 请求的初始url
self.start_url = "https://zz.lianjia.com/ershoufang/zhengdongxinqu/pg{}/"
# 定义请求头
self.headers = {"User-Agent": ua.random}
# 创建url队列
self.url_queue = Queue()
# 创建html队列
self.html_queue = Queue()
# 创建提取内容的队列
self.content_queue = Queue()
# 定义构造开始url的地址的方法
def get_url_list(self):
# 构造50个url地址
for i in range(1, 51):
# 将构造的地址加入到url队列中
self.url_queue.put(self.start_url.format(i))
# 定义解析url得到对应html文本的方法
def paser_url(self):
while True:
# 从队列中取url地址
url = self.url_queue.get()
time.sleep(0.5)
html = requests.get(url, headers=self.headers).content.decode()
# 将请求得到html文本添加到html队列中
self.html_queue.put(html)
# 将url队列中的url地址减一
self.url_queue.task_done()
# 定义得到提取信息的方法
def get_content_list(self):
while True:
# 从html队列中取html
html_str = self.html_queue.get()
e = etree.HTML(html_str)
# 提取所有的div标签
div_list = e.xpath('//ul[@class="sellListContent"]//div[@class="info clear"]')
data = []
for div in div_list:
item = {}
# 提取名称
title = div.xpath('./div[@class="title"]/a/text()')
item["title"] = title[0]
# 提取位置
positionInfo = div.xpath('./div[@class="flood"]/div[@class="positionInfo"]/a/text()')
item["positionInfo"] = positionInfo[0]
# 提取房屋信息
houseInfo = div.xpath('./div[@class="address"]/div[@class="houseInfo"]/text()')
item["houseInfo"] = houseInfo[0]
# 提取总价
total_price = div.xpath('./div[@class="priceInfo"]/div[@class="totalPrice"]/span/text()')
total_price = [i + "万" for i in total_price]
item["total_price"] = total_price[0]
# 提取单价
unit_price = div.xpath('./div[@class="priceInfo"]/div[@class="unitPrice"]/span/text()')
item["unit_price"] = unit_price[0]
# 添加进列表
data.append(item)
# 将提取的内容添加到content的队列中
self.content_queue.put(data)
# 实现html文本减一
self.html_queue.task_done()
# 定义保存文本信息的方法
def save_data(self):
# 遍历self.content_queue
for content in self.content_queue.get():
with open("lianjia2.csv", "a") as f:
for key, value in content.items():
f.write(key + ',' + value + ',')
f.write('\n')
def run(self):
thread_list = []
for i in range(10):
t_url = threading.Thread(target=self.get_url_list)
thread_list.append(t_url)
# 解析html文本的线程
for i in range(10):
t_parse = threading.Thread(target=self.paser_url)
thread_list.append(t_parse)
# 得到html文本的线程
for i in range(15):
t_html = threading.Thread(target=self.get_content_list)
thread_list.append(t_html)
# 保存提取信息的线程
for i in range(20):
t_save = threading.Thread(target=self.save_data)
thread_list.append(t_save)
# 开启线程
for t in thread_list:
t.setDaemon(True)
t.start()
# 阻塞线程,待其他线程结束之后,主线程结束
for q in [self.url_queue, self.html_queue, self.content_queue]:
q.join()
if __name__ == '__main__':
lianjia_spider = LianJiaDuo()
lianjia_spider.run()
爬取结果: