簡體   English   中英

我想從屬性內容中獲取每個家的url

[英]I want to get the urls of each home from the attribute content

const puppeteer = require("puppeteer");
const cheerio = require("cheerio");


const url = "https://www.airbnb.co.in/s/Haridwar--Uttarakhand/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&price_filter_input_type=0&price_filter_num_nights=5&l2_property_type_ids%5B%5D=1&search_type=autocomplete_click&query=Haridwar%2C%20Uttarakhand&place_id=ChIJyVfuuA5HCTkR8_VApnaRRE4&date_picker_type=calendar&source=structured_search_input_header";

async function scrapHomesPage(url)
{
    try
    {
    const browser = await puppeteer.launch({headless:false});
    const page = await browser.newPage();
    
    await page.goto(url);
    
    const html = await page.evaluate(()=> document.body.innerHTML);
    const $ =  cheerio.load(html); 
    
    const homes = $('[itemprop="url"]').map((i, element) => $(element).attr("content")).get();
    console.log(homes);
    }
    catch(err)
    {
        console.error(err);
    }
    
}

scrapHomesPage("https://www.airbnb.co.in/s/Haridwar--Uttarakhand/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_lengths%5B%5D=one_week&price_filter_input_type=0&price_filter_num_nights=5&l2_property_type_ids%5B%5D=1&search_type=autocomplete_click&query=Haridwar%2C%20Uttarakhand&place_id=ChIJyVfuuA5HCTkR8_VApnaRRE4&date_picker_type=calendar&source=structured_search_input_header");

我試圖添加所有我可以等待頁面加載所有內容的內容。 我嘗試等待選擇器等。我總是得到一個空數組,而不是我應該得到一個數組,其中包含 Airbnb 網站上針對該特定位置列出的每個房屋的所有鏈接。

我看不出有任何理由在這里使用 Cheerio。 這只是獲取所需數據的另一層間接訪問,涉及額外的依賴關系、頁面的第二次解析以及當頁面與您創建的 HTML 快照不同步時可能出現錯誤。 如果確實需要使用它,可以使用page.content()而不是page.evaluate(() => document.body.innerHTML)

至於主要問題,您似乎缺少對page.waitForSelector的調用:

const puppeteer = require("puppeteer"); // ^19.0.0

const url = "your url";

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  await page.goto(url, {waitUntil: "domcontentloaded"});
  await page.waitForSelector('[itemprop="url"]');
  const content = await page.$$eval(
    '[itemprop="url"]',
    els => els.map(el => el.getAttribute("content"))
  );
  console.log(content);
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM