【问题标题】:I want to get the urls of each home from the attribute content我想从属性内容中获取每个家的url
【发布时间】:2022-12-18 21:30:51
【问题描述】:
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 网站上针对该特定位置列出的每个房屋的所有链接。

【问题讨论】:

  • “我试过等待选择器等”——这是正确的方法,所以你可能想展示这种尝试……

标签: javascript node.js puppeteer


【解决方案1】:

我没有看到 any reason 在这里使用 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());

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2011-07-29
    相关资源
    最近更新 更多