文章目录
- 1. 实战概述
- 2. 网站页面分析
- 3. 编写代码爬取Q房二手房房源信息
-
- 4. 实战小结
1. 实战概述
- 本次实战项目旨在通过编写Python爬虫程序,抓取深圳Q房网上的二手房房源信息。我们将分析网页结构,确定房源信息的XPath路径,并实现数据的提取与CSV文件存储。通过本项目,学习如何运用requests库发送HTTP请求,使用lxml.etree解析HTML,以及如何高效地处理和存储爬取的数据。
2. 网站页面分析
- 第1页房源 - https://shenzhen.qfang.com/sale/f1

- 第2页房源 - https://shenzhen.qfang.com/sale/f2

- 发现URL构造规律:
https://shenzhen.qfang.com/sale/f
+ 页码
- 查看房源列表源码

- 针对第一个
li
,拷贝其XPath
://*[@id="cycleListings"]/ul/li[1]
,去掉[1]
,根据//*[@id="cycleListings"]/ul/li
获取房源列表 - 针对每一个房源,要爬取的信息用红框标注

3. 编写代码爬取Q房二手房房源信息
3.1 创建项目与程序
- 创建
Q房网爬虫实例
项目,在里面创建QHouseCrawler.py
程序

from lxml import etree
import requests
import csv
import time
def spider():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
}
url_prefix = "https://shenzhen.qfang.com/sale/f"
for page in range(1, 11):
url = url_prefix + str(page)
html = requests.get(url, headers=headers)
time.sleep(2)
selector = etree.HTML(html.text)
house_list = selector.xpath('//*[@id="cycleListings"]/ul/li')
for house in house_list:
apartment = house.xpath('div[2]/div[1]/a/text()')[0]
house_layout = house.xpath('div[2]/div[2]/p[1]/text()')[0]
area = house.xpath('div[2]/div[2]/p[2]/text()')[0]
region = house.xpath('div[2]/div[4]/text()')[0]
item = [apartment, house_layout, area, region]
cleaned_item = [i.replace('\r', '').replace('\n', '').replace(' ', '') for i in item]
data_writer(cleaned_item)
print('正在抓取……', cleaned_item)
def data_writer(item):
with open('Q房-二手房.csv', 'a',
encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(item)
if __name__ == '__main__':
spider()
3.2 运行程序,查看结果
4. 实战小结
- 在本次实战中,我们成功地分析了深圳Q房网二手房页面的结构,掌握了房源信息的XPath定位方法。通过编写Python爬虫脚本,我们实现了从网页动态加载的房源列表中提取关键信息,并将数据存储至CSV文件。在实践过程中,我们遇到了XPath表达式的优化和数据清洗的问题,但通过不断调试和改进,最终达到了预期效果。此项目不仅提升了我们的爬虫编写技能,也加深了对网页结构和数据提取流程的理解,为今后处理更复杂的数据抓取任务打下了坚实基础。