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

如何使用Puppeteer获取指定ul标签下的首个房源链接?

提取房产网站最新房源链接的Puppeteer代码修改方案

你需要从带有data-testid="results"属性的<ul>下第一个<li>内的<a>标签提取href属性,替代原有获取所有链接的逻辑,具体修改如下:

现有代码问题

原有代码通过document.querySelectorAll("a[href]")获取页面所有带href的链接,无法精准定位到目标房源链接。

修改后的完整代码

const puppeteer = require("puppeteer");

const link =
  "https://www.daft.ie/property-for-rent/dublin-4-dublin?radius=5000&numBeds_from=2&numBeds_to=3&sort=publishDateDesc";

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
  });
  const page = await browser.newPage();
  await page.goto(link);

  // 处理Cookie弹窗
  const elements = await page.$x("//button[normalize-space()='Accept All']");
  if (elements.length > 0) {
    await elements[0].click();
  }

  // 等待结果列表加载完成,确保元素存在
  await page.waitForSelector('ul[data-testid="results"] li:first-child a[href]');

  // 提取第一个房源的href链接
  const latestHref = await page.evaluate(() => {
    const firstListingAnchor = document.querySelector('ul[data-testid="results"] li:first-child a[href]');
    return firstListingAnchor ? firstListingAnchor.getAttribute('href') : null;
  });

  console.log(latestHref); // 输出示例:/for-rent/house-glencloy-road-whitehall-dublin-9/4072150

  await browser.close();
})();

关键改动说明

  1. 等待元素加载:使用page.waitForSelector确保目标房源元素完全加载,避免因页面异步渲染导致获取不到元素。
  2. 精准定位元素:通过document.querySelector('ul[data-testid="results"] li:first-child a[href]')直接定位到第一个房源的<a>标签,其中:
    • ul[data-testid="results"]:匹配指定属性的列表容器
    • li:first-child:选中列表下第一个房源项
    • a[href]:选中房源项内带href的链接标签
  3. 安全取值:添加空值判断,避免因元素不存在导致报错。

备选方案(XPath方式)

如果你更习惯用XPath定位,也可以替换成以下代码段:

// 等待并获取第一个房源的a标签
const [firstAnchor] = await page.$x('//ul[@data-testid="results"]/li[1]/a[@href]');
const latestHref = await page.evaluate(anchor => anchor.getAttribute('href'), firstAnchor);
console.log(latestHref);

内容的提问来源于stack exchange,提问作者alex deralu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:31:20