最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Puppeteer Get data attribute contains selector - Stack Overflow

programmeradmin1浏览0评论

Markup on localhost

<ul>
 <li>
  <button data-action-trigger="btn1">Button text</button>
 </li>
</ul>

I need to click on btn1 by selecting it with its data-attribute value btn I get an empty object in the console.log

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({width: 1440, height: 1200})
  await page.goto('http://localhost:3000/index.html')

  const data = await page.content();

  const btnAction = await page.evaluate(
      () => document.querySelector('[data-action-trigger*="btn1"]'))

  console.log(btnAction) //{}

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

I am able to select the element Chrome devTools as

document.querySelector(`[data-action-trigger*="btn1"]`)
<button data-action-trigger="btn1">Button text</button>

Markup on localhost

<ul>
 <li>
  <button data-action-trigger="btn1">Button text</button>
 </li>
</ul>

I need to click on btn1 by selecting it with its data-attribute value btn I get an empty object in the console.log

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({width: 1440, height: 1200})
  await page.goto('http://localhost:3000/index.html')

  const data = await page.content();

  const btnAction = await page.evaluate(
      () => document.querySelector('[data-action-trigger*="btn1"]'))

  console.log(btnAction) //{}

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

I am able to select the element Chrome devTools as

document.querySelector(`[data-action-trigger*="btn1"]`)
<button data-action-trigger="btn1">Button text</button>
Share Improve this question asked Jan 30, 2020 at 0:33 zadubzzadubz 1,3012 gold badges21 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

From the docs:

The only difference between page.evaluate and page.evaluateHandle is that page.evaluateHandle returns in-page object (JSHandle).

Since it's returning an in-page object, you need to use evaluateHandle instead of evaluate.

await page.waitForSelector('[data-action-trigger*="btn1"]');
const btnAction = await page.evaluateHandle(() => document.querySelector('[data-action-trigger*="btn1"]'))

Alternatively, you can use page.$:

await page.waitForSelector('[data-action-trigger*="btn1"]');
const btnAction = await page.$('[data-action-trigger*="btn1"]');
发布评论

评论列表(0)

  1. 暂无评论