【问题标题】:How select an element by xpath and click on it with puppeteer?如何通过 xpath 选择一个元素并用 puppeteer 点击它?
【发布时间】:2020-09-29 23:06:40
【问题描述】:

我试过这个简单的例子来点击一个链接,但它似乎不起作用。 该示例基本上是单击 youtube.com 中的登录按钮 错误抛出

(node:12304) UnhandledPromiseRejectionWarning: TypeError: youtubeLoginButton.evaluate is not a function
    at C:\Users\GoodBoy\Desktop\code\Puppeteer\scrape-content-from-website\bot.js:17:30
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:12304) 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:12304) [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.
const puppeteer = require('puppeteer')

;(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        args: ['--start-maximized'],
    })
    const page = await browser.newPage()

    await page.goto('https://www.youtube.com/')

    const youtubeLoginButtonXpath = '//*[@id="buttons"]/ytd-button-renderer/a'

    const youtubeLoginButton = await page.$x(youtubeLoginButtonXpath)

    await youtubeLoginButton.evaluate((form) => form.click())

    await browser.close()
})()

【问题讨论】:

    标签: javascript node.js xpath automation puppeteer


    【解决方案1】:

    这应该可以工作(我已经修改了一点你的 XPath):

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.youtube.com',{ waitUntil: 'networkidle2' });
    const elements = await page.$x('(//div[@id="buttons"]/ytd-button-renderer/a)[1]')
    await elements[0].click() 
    await page.screenshot({path: 'full.png', fullPage: true});
    await browser.close();
    

    输出:登录页面截图(上传新视频)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2021-02-13
      • 2016-07-24
      相关资源
      最近更新 更多