[英]How to click and hold in Puppeteer
我正在嘗試使用 Puppeteer 單擊並按住。 我嘗試在while
循環中使用page.click
但它沒有用。
let browserURL = `http://127.0.0.1:9222`;
let browser = await puppeteer.connect({ browserURL, defaultViewport: null });
const page = await browser.newPage();
while (pageContent.includes("hold")) {
await page.click("div")
}
我也試過這個:
await page.mouse.click(132, 103, { button: 'left' })
任何想法如何做到這一點?
在 Puppeteer 中有一些工具可以觸發鼠標按住: page.click
、 mouse.click
、 mouse.down
和mouse.up
。 page.hover
可用於將鼠標定位在選擇器上,而mouse.move
可用於基於坐標的定位和實現單擊和拖動。
然后,還有page.evaluate
(和 family),它允許您運行瀏覽器代碼來觸發目標元素上的本機mousedown
和mouseup
事件。 如果您在點擊 Puppeteer 功能時遇到困難(例如,由於可見性問題), evaluate
是一個不錯的下一個嘗試選項。
您選擇哪種方法取決於您的用例。 如果您使用.click()
調用(這些是page.hover
、 mouse.move()
、 mouse.down()
和mouse.up()
上的便利包裝器),您將需要在選項上設置delay
屬性對象來模擬保持,文檔描述為
delay
<number> 在 mousedown 和 mouseup 之間等待的時間(以毫秒為單位)。 默認為 0。
這是以下按鈕的概念證明:
const hms = () => ("" + Date()).slice(16, 24); const btnEl = document.querySelector("button"); btnEl.addEventListener("mousedown", e => { document.querySelector("ul").innerHTML += `<li>mousedown at ${hms()}</li>` ; }); btnEl.addEventListener("mouseup", e => { document.querySelector("ul").innerHTML += `<li>mouseup at ${hms()}</li>` ; });
<button>click and hold me</button> <ul></ul>
const puppeteer = require("puppeteer");
let browser;
(async () => {
const html = `
<button>click and hold me</button>
<ul></ul>
<script>
const hms = () => ("" + Date()).slice(16, 24);
const btnEl = document.querySelector("button");
btnEl.addEventListener("mousedown", e => {
document.querySelector("ul").innerHTML +=
\`<li>mousedown at \${hms()}</li>\`
;
});
btnEl.addEventListener("mouseup", e => {
document.querySelector("ul").innerHTML +=
\`<li>mouseup at \${hms()}</li>\`
;
});
</script>
`;
browser = await puppeteer.launch({headless: false});
const [page] = await browser.pages();
await page.setContent(html);
await page.click("button", {delay: 5000});
await page.waitForFunction(() =>
document.querySelector("ul").innerText.includes("mouseup")
);
console.log(await page.$eval("ul", el => el.innerText));
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;
輸出是這樣的
mousedown at 12:53:23
mouseup at 12:53:28
這表明鼠標在按鈕上按住了 5 秒鍾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.