簡體   English   中英

Puppeter-在iFrame中鏈接

[英]Puppeter - Link inside an iFrame

我必須在此頁面的要點下方找到廣告鏈接。

我正在與Puppeter一起嘗試,但由於廣告是iframe,因此遇到了麻煩!

我可以使用Chrome控制台成功獲得所需的東西:

document.querySelector('#adContainer a').href

Puppetter

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({width: 1440, height: 1000})
  await page.goto('https://www.amazon.co.uk/dp/B07DDDB34D', {waitUntil: 'networkidle2'})

  await page.waitFor(2500);

  const elementHandle = await page.$eval('#adContainer a', el => el.href);

  console.log(elementHandle);
  await page.screenshot({path: 'example.png', fullPage: false});

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

錯誤:錯誤:找不到與選擇器“ #adContainer a”匹配的元素

在此處輸入圖片說明

編輯:

const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({width: 1440, height: 1000})
  await page.goto('https://www.amazon.co.uk/dp/B07DDDB34D', {waitUntil: 'networkidle2'})

const adFrame = page.frames().find(frame => frame.name().includes('"adServer":"cs'))
const urlSelector = '#sp_hqp_shared_inner > div > a';
const url = await adFrame.$eval(urlSelector, element => element.textContent);
console.log(url);


  await browser.close();

運行https : //try-puppeteer.appspot.com/

您需要在框架內部進行查詢,可以通過page.frames()進行訪問:

const adFrame = page.frames().find(frame => frame.name().includes('<some text only appearing in name of this iFrame>');
const urlSelector = '#sp_hqp_shared_inner > div > a';
const url = await adFrame.$eval(urlSelector, element => element.textContent);
console.log(url);

我如何獲得該網址的選擇器: 在此處輸入圖片說明

告白,我自己還沒有嘗試過。 另外,我認為在iFrame中獲取該url的適當方法是這樣的

const url = await adFrame.evaluate((sel) => {
  return document.querySelectorAll(sel)[0].href;
}, urlSelector);

每次頁面加載時,您都必須切換到要處理的框架。

async getRequiredLink() {
    return await this.page.evaluate(() => {
        let iframe = document.getElementById('frame_id'); //pass id of your frame
        let doc = iframe.contentDocument; // changing the context to the working frame
        let ele = doc.querySelector('you-selector'); // selecting the required element
        return ele.href;
    });
}

暫無
暫無

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

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