페이지에서 '바구니에 추가'버튼 요소를 모두 긁어내어 배열에 넣고 해당 배열을 Node 환경으로 반환하는 다음 코드가 있습니다.
const puppeteer = require('puppeteer');
let getArrayofButtons = async () => {
const browser = await puppeteer.launch({
devtools: 'true',
});
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 1800 });
await page.goto('http://books.toscrape.com/', {
waitUntil: 'domcontentloaded',
});
await page.waitForSelector('.product_pod');
let buttons = [];
await page.evaluate(() => {
buttons = [...document.querySelectorAll('*')].filter(e =>
[...e.childNodes].find(n => n.nodeValue?.match('basket'))
);
console.log(buttons);
});
// browser.close();
};
getArrayofButtons().then(returnedButtons => {
console.log(returnedButtons);
});
나는 때 console.log(buttons);
나는의 배열을 볼 수있는 button
브라우저 환경의 요소를,하지만 난 얻을 노드 환경에 그 배열을 반환 할 때 undefined
.
내 이해는 page.evaluate()
전달 된 함수의 값을 반환하므로 다음을 대체하면
articles = [...document.querySelectorAll('*')].filter(e => [...e.childNodes].find(n => n.nodeValue?.match('basket')) );
와:
return [...document.querySelectorAll('*')].filter(e => [...e.childNodes].find(n => n.nodeValue?.match('basket')) );
작동해야하는 것 같습니다. Promise가 올바르게 해결되지 않았습니까?
해당 결과에 evaluateHandle
대한 포인터 를 얻기 위해 호출 할 수 있습니다.
const arrayHandle = await page.evaluateHandle(() => {
buttons = [...document.querySelectorAll('*')].filter(e =>
[...e.childNodes].find(n => n.nodeValue?.match('basket'))
);
return buttons;
});
공지 사항 arrayHandle
배열이 아닙니다. 그것은이다 ElementHandle
브라우저의 배열을 가리키는.
측면의 각 버튼을 처리하려면 해당 getProperties
함수를 호출하는 핸들을 처리해야 합니다.
const properties = await arrayHandle.getProperties();
await arrayHandle.dispose();
const buttons = [];
for (const property of properties.values()) {
const elementHandle = property.asElement();
if (elementHandle)
buttons.push(elementHandle);
}
예, 꽤 상용구입니다. 그러나 그 핸들을 잡고 평가 함수에 전달할 수 있습니다.
page.evaluate((elements) => elements[0].click(), arrayHandle);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다