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

javascript - Getting a Dynamic Element by Selector - Stack Overflow

programmeradmin0浏览0评论

I need to click to a certain web button with the id: #product-6852370-Size.

I am working with Puppeteer, so normally I would do:

page.click('#product-6852370-Size');

The tricky part is that the number 6852370 is dynamic and changes every time I refresh the page.

So what I need is a piece of code that is saying:

Search for id's that include product- and -size. Any way that this might happen?

I need to click to a certain web button with the id: #product-6852370-Size.

I am working with Puppeteer, so normally I would do:

page.click('#product-6852370-Size');

The tricky part is that the number 6852370 is dynamic and changes every time I refresh the page.

So what I need is a piece of code that is saying:

Search for id's that include product- and -size. Any way that this might happen?

Share Improve this question edited Jul 22, 2018 at 5:27 Grant Miller 29k16 gold badges155 silver badges168 bronze badges asked Jul 21, 2018 at 18:15 TyphoonTyphoon 1882 silver badges10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

You can match the beginning and end of the id attribute using:

await page.click('[id^="product-"][id$="-Size"]');

Or, more accurately, you can ensure that a number is present in the middle of your id using regex:

await page.evaluate(() => {
  [...document.querySelectorAll('[id^="product-"][id$="-Size"]')].filter(e => e.id.match(/^product-\d+-Size$/g))[0].click();
});

You may use attribute starts with selector to do that:

page.click('button[id^="product-"]')
发布评论

评论列表(0)

  1. 暂无评论