我正在尝试web抓取,但我遇到了这个小问题。我想刮的网站有两个按钮,都属于同一类。使用Puppeteer,我想点击第二个按钮。问题是,当我必须在click函数中执行字符串jQuery时,我不知道如何选择第二个元素。
page.click('.ws-collapsable-block__heading')
上面的行非常适合点击第一个按钮,但正如我所说,我正在尝试点击第二个按钮。我试过:
page.click('.ws-collapsable-block__heading:eq(1)')
page.click('.ws-collapsable-block__heading').eq(1)
page.click('.ws-collapsable-block__heading'.eq(1))
page.click('.ws-collapsable-block__heading'[1])
page.click('.ws-collapsable-block__heading')[1]
但它们都不起作用。
我的第二个解决方案是使用传统的jQueryDOM搜索,如下所示:
document.querySelector('.ws-collapsable-block__heading')
但我不能访问页面评估之外的"文档",也不能访问评估内部的页面。
下面的完整脚本:
const puppeteer = require('puppeteer')
async function get_info(code) {
let url = 'https://joker.no/sok?query=' + code
let browser = await puppeteer.launch()
let page = await browser.newPage()
await page.goto(url, { waitUntil: 'networkidle2' })
let get_link = await page.evaluate(() => document.querySelector('.ws-product__title').getAttribute('href') )
let product_name = await page.evaluate(() => document.querySelector('.ws-product__title').innerText );
await page.goto('https://joker.no' + get_link)
// This clicks the first button...
page.click('.ws-collapsable-block__heading')
await page.screenshot({path: 'x.png'})
}
get_info('7311041013663')
编辑:我试过像这个一样使用第n个
page.click('.ws-collapsable-block__heading:nth-child(2)')
但它给出了这个错误
(node:5856) UnhandledPromiseRejectionWarning: Error: No node found for selector: .ws-collapsable-block__heading:nth-child(2)
at assert (E:NodeKaloriAppnode_modulespuppeteerlibhelper.js:283:11)
at DOMWorld.click (E:NodeKaloriAppnode_modulespuppeteerlibDOMWorld.js:366:5)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at Frame.<anonymous> (E:NodeKaloriAppnode_modulespuppeteerlibhelper.js:111:15)
at Page.click (E:NodeKaloriAppnode_modulespuppeteerlibPage.js:1067:29)
at get_info (E:NodeKaloriAppapp.js:17:10)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:5856) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5856) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
如果我在网站上尝试document.querySelectorAll('.ws-collapsable-block__heading:nthe-child(1('(,我会得到一个大小为3的nodeList。不过,我仍然需要执行document.querySelectorAll('.ws-collapsable-block__heading:nh-child(1('([1]来获取第二个元素,而我似乎无法在单击函数中执行此操作。
您可以使用page.$$
方法轻松获取所有产品,然后单击其中一个。不要忘记添加await
。
例如:
const [ firstProduct, secondProduct, thirdProduct ] = await page.$$('.ws-panel');
await secondProduct.click(); // click the second button
使用第n个子选择器
page.click('.ws-collapsable-block__heading:nth-child(2)')