You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium定位动态XPath房源元素:解决仅获单个房源问题

解决房产房源数据抓取的Selenium定位问题

问题核心分析

当前代码存在两个关键问题:

  • 使用绝对XPath并固定了房源ID(如link_ad_71883344),导致只能定位单个房源,无法遍历所有条目。
  • 未使用相对路径从每个offer元素内部查找子节点,而是全局搜索,引发NoSuchElementException(部分房源结构可能不同,或全局搜索找不到对应元素)。

修正方案

以下是优化后的代码,解决定位问题并添加去重逻辑:

import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

url = "https://www.immobiliare.it/search-list/?idContratto=1&idCategoria=1&idTipologia%5B0%5D=7&idTipologia%5B1%5D=31&idTipologia%5B2%5D=11&idTipologia%5B3%5D=12&criterio=rilevanza&__lang=it&fkRegione=tos&idProvincia=LI&idNazione=IT&pag=1"

driver = webdriver.Edge()
driver.get(url)

# 定位所有房源容器(过滤无关元素,只保留有效房源条目)
offers = driver.find_elements(By.XPATH, "//div[contains(@class, 'nd-list__item') and contains(@id, 'ad_')]")

offer_list = []
seen_ids = set()  # 用于去重的唯一ID集合

for offer in offers:
    try:
        # 提取房源唯一ID(从容器ID中解析)
        offer_id = offer.get_attribute("id").replace("ad_", "")
        if offer_id in seen_ids:
            continue  # 跳过重复房源
        seen_ids.add(offer_id)
        
        # 使用相对XPath从当前offer元素内部查找子节点
        title = offer.find_element(By.XPATH, ".//a[contains(@id, 'link_ad_')]").text
        area = offer.find_element(By.XPATH, ".//li[contains(@class, 'nd-list__item-feature--surface')]/div").text
        price = offer.find_element(By.XPATH, ".//div[contains(@class, 'nd-list__item-price')]").text
        
        offer_list.append({
            "id": offer_id,
            "title": title,
            "area": area,
            "price": price
        })
    except NoSuchElementException:
        # 跳过结构异常的房源,避免遍历中断
        continue

# 转换为DataFrame查看结果
df = pd.DataFrame(offer_list)
print(df)

driver.quit()

关键优化点

  • 相对路径定位:所有子元素查找使用.//开头,确保仅在当前房源容器内搜索,避免全局定位错误。
  • 动态ID适配:通过contains()语法匹配包含固定前缀的ID/类名,不依赖具体数值。
  • 异常处理:用try-except捕获NoSuchElementException,跳过结构不一致的房源,保证遍历完整。
  • 去重逻辑:通过房源唯一ID集合过滤重复条目,解决重复显示问题。

内容的提问来源于stack exchange,提问作者Wojtek Cajzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:43:14