javascript - Node JS Puppeteer 单击没有名称或 ID 的 li 元素

标签 javascript node.js puppeteer

我试图点击一个 li 元素,由于某种原因,它在某个网站上用作尺寸选择器。看起来像这样

size selector

它的 html 看起来像这样

enter image description here

每个<li>代表一种尺寸选项,我已经尝试了一些东西,但都没有用。

我的第一次尝试是使用 xpath:

const [size_button] = await page.$x(`//*[contains(., '${data[ii][1]}')]`); // doesn't work
await size_button.click();

我还尝试了常规的点击操作:

await page.click(`li[data-original-title="Größe in EU: ${data[ii][1]}"]`); // the array contains a specific size, eg. 40.5 like in the li data-original-title field

这些都不起作用,我想知道是否有可能用 puppeteer 点击这样的元素......

如果有人想查看该页面,链接是 here

最佳答案

这有点棘手。你的选择器工作正常,点击事件也是如此,但我怀疑该事件除了调用 e.preventDefault() 什么都不做。以防止导航到 anchor 的 href。

显示尺寸被选中的突出显示实际上是由 mousedown 应用的<a> 中的事件的 parent <li> ,而且似乎子事件尚未应用或未使用您的 .click 冒泡方法:

image showing browser console element tree with the li element's mousedown event circled to indicate it's the important event OP wants to trigger

您可以按如下方式触发:

const puppeteer = require("puppeteer"); // ^13.5.1

let browser;
(async () => {
  browser = await puppeteer.launch({headless: false});
  const [page] = await browser.pages();
  await page.setRequestInterception(true);
  page.on("request", req => {
    req.resourceType() === "image" ? req.abort() : req.continue();
  });
  const url = "https://en.afew-store.com/products/air-jordan-4-retro-tour-yellow-dark-blue-grey-white";
  await page.goto(url, {waitUntil: "domcontentloaded"});
  const size = "8.5";
  const xp = `//a[contains(@class, "btn-sm") and text()="${size}"]`;
  const sizeButton = await page.waitForXPath(xp);
  await sizeButton.evaluate(btn => {
    btn.closest("li").dispatchEvent(new Event("mousedown"));
    //  ^--- .parentNode is also possible instead of .closest("li")
  });
  await page.waitForTimeout(10000);
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;

最后的超时让您有机会查看页面并看到大小 8.5 已突出显示。

请注意,我已经使您的 xpath 选择器更加精确以避免误报。

关于javascript - Node JS Puppeteer 单击没有名称或 ID 的 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68911769/

相关文章:

javascript - Node JS Jasmine 使用 jasmine.any() 测试多种类型

node.js - 如何使用 node-fetch、supertest 和 typescript 设置 fetch-mock

jestjs - 如何在 puppeteer 中获取重定向状态?

javascript - 如何让一个函数在每次收到另一个函数的输出时执行? ( Node JS)

javascript - 如何使用 AngularJS 将字符串作为函数执行?

javascript - 如何使用 Bluebird promise Node 的 child_process.exec 和 child_process.execFile 函数?

javascript - 未识别的数据结构-转换为对象

javascript - JS 使用两个数组

windows - 使用 puppeteer、windows 在 chromium 中播放 mp4

javascript - 记录 Puppeteer Node.js 进程中客户端代码中进行的 `console` 调用