如何使用 Puppeteer 单击网站上的按钮,而没有分配任何类、id、...? [英] How to click a button on a website using Puppeteer without any class, id ,... assigned to it?

查看:29
本文介绍了如何使用 Puppeteer 单击网站上的按钮,而没有分配任何类、id、...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想点击网站上的一个按钮.该按钮没有 id、class、...所以我应该找到一种方法来单击上面带有名称的按钮.在这个例子中,我应该点击名称Supreme®/TheNorth Face® 皮革单肩包"

So I want to click on a button on a website. The button has no id, class,... So I should find a way to click the button with the name that's on it. In this example I should click by the name "Supreme®/The North Face® Leather Shoulder Bag"

这是我在 Node.js 中的代码

This is my code in Node.js

const puppeteer = require('puppeteer');

let scrape = async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('https://www.supremenewyork.com/shop/all/bags');
await page.click(...);
browser.close();
return result;
};

这是我要点击的元素:

<a class="name-link" href="/shop/bags/a9cz4te2r/rsth86fbl">Supreme®/The 
North Face® Leather Shoulder Bag</a>

推荐答案

这是一种收集数据的方法.首先在浏览器控制台上尝试这些.

Here is a way to collect that data. Try these on your browsers console first.

[...document.querySelectorAll('a.name-link')]
.filter(element => 
  element.innerText.includes('Supreme®/The North Face® Leather Shoulder Bag')
)

这是怎么回事?

  • document.querySelectorAll 查找具有该选择器的所有元素.
  • .filter 将返回与查询匹配的结果.
  • .includes 将返回包含给定字符串的数据.
  • document.querySelectorAll finds all element with that selector.
  • .filter will return the result that matches the query.
  • .includes will return data that includes a given string.

如果 a.name-link 不起作用,则查找 a,如果不起作用,则找到父项并使用它.

If a.name-link does not work, then look for a, if that does not work, then find the parent item and use that.

在浏览器上获得元素后,您可以将其应用到代码中,单击它等.

Once you got the element on your browser, you can apply that on your code, click it etc.

您可以使用 page.evaluate 进行过滤和点击.

You can use page.evaluate to filter and click.

const query = "Supreme®/The North Face® Leather Shoulder Bag";

page.evaluate(query => {
  const elements = [...document.querySelectorAll('a.name-link')];

  // Either use .find or .filter, comment one of these
  // find element with find
  const targetElement = elements.find(e => e.innerText.includes(query));

  // OR, find element with filter
  // const targetElement = elements.filter(e => e.innerText.includes(query))[0];

  // make sure the element exists, and only then click it
  targetElement && targetElement.click();
}, query)

这篇关于如何使用 Puppeteer 单击网站上的按钮,而没有分配任何类、id、...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆