如何使用Puppeteer在未分配任何类,ID ...的情况下单击网站上的按钮? [英] How to click a button on a website using Puppeteer without any class, id ,... assigned to it?

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

问题描述

因此,我想单击网站上的按钮.该按钮没有id,class等.因此,我应该找到一种方法来单击带有其名称的按钮.在此示例中,我应单击名称Supreme®/TheNorthFace®皮革单肩包"

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天全站免登陆