【Scrapy爬取实例】- 爬取链家网指定城市二手房源信息

一、网站分析
  • 链接分析
    • 城市链接
      北京:https://bj.lianjia.com/ershoufang/
      成都:https://cd.lianjia.com/ershoufang/
      四川:https://sc.lianjia.com/ershoufang/

      可见,不同城市,将标红处改为城市的首字母小写即可。
    • 页面链接
      第一页:https://cd.lianjia.com/ershoufang/pg1
      第二页:https://cd.lianjia.com/ershoufang/pg2
      第三页:https://cd.lianjia.com/ershoufang/pg3

      可见,将标红处依次递增即可。
  • 数据加载方式
    链家的比较简单,网页源码里都有
    数据加载方式
  • 目标信息
    目标信息
    本次抓取目标为上图红框中的关键文字信息。
二、抓取思路

因为信息都在网页源码中,页面链接的生成规律也很简单,所以解决如何生成指定城市的链接即可。
由上述分析可知,城市链接只要将城市名称,如 重庆转为首字母小写 cq,再填入对应位置即可。
其他:

  • 设置请求头、免费代理ip实时切换,处理请求异常
  • 抓取到的信息存入mongodb
三、关键代码
  • item
import scrapy
class ErshoufangItem(scrapy.Item):
    # define the fields for your item here like: 
    title = scrapy.Field() #房屋title
    address = scrapy.Field() #地址
    city = scrapy.Field()#所在城市
    info = scrapy.Field()#具体信息
    totalPrice = scrapy.Field()#总价
    unitPrice = scrapy.Field()#单价
  • spider
import scrapy
from xpinyin import Pinyin #汉字转拼音的库

from ershoufang.items import ErshoufangItem

pinyin = Pinyin()
CRAWL_PAGE = 10 #爬取页数

class LianjiaSpider(scrapy.Spider):
    name = 'lianjia'
    def __init__(sel
### 使用Python编写虫抓取二手房房价数据 为了实现这一目标,通常会选择适合的库和技术栈来简化开发过程并提高效率。根据已有研究[^1],Python中的`Requests`库和`BeautifulSoup`库被广泛应用于页解析与数据获取;此外,还有专门设计用于复杂任务场景下的Scrapy框架可供选择。 #### 准备工作 在开始之前,确保安装必要的依赖项: ```bash pip install requests beautifulsoup4 lxml pandas openpyxl ``` 这些包分别负责HTTP请求发送(`requests`)、HTML/XML文档解析(`beautifulsoup4`, `lxml`)以及数据分析处理(`pandas`)等功能模块的支持。 #### 获取页面内容 构建基础版本的虫脚本如下所示: ```python import requests from bs4 import BeautifulSoup def fetch_page(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', } response = requests.get(url, headers=headers) if response.status_code != 200: raise Exception(f"Failed to load page {url}") soup = BeautifulSoup(response.text, "html.parser") return soup ``` 这段代码定义了一个名为`fetch_page()`的功能函数,用来发起GET请求访问指定URL地址所指向的目标站点,并返回经过初步清理后的HTML码对象以便后续操作。注意设置合理的User-Agent头信息模拟正常浏览器行为以规避部分简单的反措施[^2]。 #### 提取所需字段 针对具体案例——即上的二手住宅详情页结构特点,定位到包含有用信息的关键标签节点路径后即可着手实施具体的抽取逻辑: ```python def parse_house_info(soup): house_listings = [] items = soup.find_all('li', class_='clear') # 查找所有符合条件的商品条目 for item in items[:min(70,len(items))]: # 控制每次读取的数量不超过70条记录以防触发频率限制 try: title = item.select_one('.title a').get_text(strip=True) total_price = float(item.select_one('.totalPrice span').text.strip()) unit_price = int(item.select_one('.unitPriceValue').text.replace(',', '').strip()[:-1]) location_parts = item.select_one('.positionInfo a').get_text().split('-') district = location_parts[0].strip() community_name = '-'.join(location_parts[1:]).strip() floor_info = item.select_one('.houseInfo').contents[-1].replace('\n', '').strip() layout = item.select_one('.houseInfo').select_one('a').string listing = { 'Title': title, 'Total_Price': total_price, 'Unit_Price': unit_price, 'District': district, 'Community_Name': community_name, 'Floor_Info': floor_info, 'Layout': layout } house_listings.append(listing) except AttributeError as e: continue return house_listings ``` 上述方法实现了对每一页内多个房列表项目的遍历循环,从中抽取出诸如标题、总售价、单位面积价格等核心属性值存入字典容器中形成一条完整的记录实例。考虑到实际运行过程中可能出现异常情况(比如某些元素缺失),因此加入了基本错误捕捉机制保证程序稳定性[^3]。 #### 存储结果至文件 最后一步就是将收集整理完毕的数据集导出保存下来供进一步加工分析之用: ```python import pandas as pd dataframe = pd.DataFrame(house_listings) output_file_path = './houses.xlsx' dataframe.to_excel(output_file_path, index=False) print(f'Data has been saved into "{output_file_path}" successfully.') ``` 这里借助Pandas库提供的便捷接口快速完成了Excel表格形式的结果输出功能,同时也支持CSV等多种常见格式的选择切换[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值