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

如何为目标房产网站编写正确XPath以实现数据爬取?

网页无法下载的解决方法

该网站存在反爬机制,需模拟浏览器请求绕过限制:

  • curl 模拟浏览器请求:添加浏览器UA头,若仍失败,可手动从浏览器复制Cookie后加入请求
    curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" \
         --cookie "your_browser_cookies_here" \
         https://firenze.bakeca.it/annunci/tutte-le-categorie/luogo/Fucecchio/ > page.html
    
  • 用xidel渲染动态内容:该网站大概率是JS动态加载页面,xidel可通过内置JS引擎渲染完整内容,直接抓取:
    xidel --javascript https://firenze.bakeca.it/annunci/tutte-le-categorie/luogo/Fucecchio/ --output-format html > rendered_page.html
    
XPath err:XPTY0004 错误解决

这个错误是XPath表达式类型不匹配导致的,常见原因及修复方式:

  1. 动态内容未加载:静态抓取的HTML里没有目标元素,强行用XPath定位会返回非节点类型,触发类型错误。必须用上面的--javascript参数让xidel获取渲染后的完整页面。
  2. XPath表达式逻辑错误:比如误将属性当作节点调用,或用节点集函数处理单个值。举个示例(需根据实际页面结构调整):
    假设广告项是div.annuncio-item,价格在span.price中,正确的XPath应写为:
    //div[contains(@class, 'annuncio-item')]/span[contains(@class, 'price')]/text()
    
    若错误写成//div[contains(@class, 'annuncio-item')]/@price(实际无此属性),就会返回空值或触发类型不匹配。
  3. 强制类型转换:如果需要将文本转为数字(比如价格),用number()函数显式转换:
    number(//span[@class='price']/text())
    
完整爬虫脚本示例

假设页面渲染后广告结构为div.annuncio-card,包含所需字段,脚本如下:

xidel --javascript https://firenze.bakeca.it/annunci/tutte-le-categorie/luogo/Fucecchio/ -e '
  //div[contains(@class, "annuncio-card")]/(
    "价格: " || span[contains(@class, "price")]/text(),
    "链接: " || a[@class="annuncio-link"]/@href,
    "描述: " || p[contains(@class, "description")]/text(),
    "面积: " || span[contains(@class, "area")]/text(),
    "---"
  )
'

注意:实际XPath需根据浏览器开发者工具查看的真实页面结构调整。

内容的提问来源于stack exchange,提问作者eofficecom com

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:15:00