0

我正在尝试在 Pyppeteer 中使用page.evaluate捕获js 脚本响应,但我无法捕获它。在下面的代码中,我试图在尺寸变量中捕获 js 脚本返回的结果,但它的捕获为None

import asyncio
from pyppeteer import launch
async def hmm():
    browser = await launch(headless=False)
    page = await browser.newPage()
    await page.goto('https://jobs.chegg.com')
    dimensions = await page.evaluate("""async () => {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/3.1.2/axe.min.js';
        document.head.appendChild(script);
        var result = new Promise((resolve, reject) => {
            axe.run(document, {
            runOnly: {
                type: "tag",
                values: ["wcag2a", "wcag2aa", "best-practice"]
            },
            "rules": {
                "skip-link": { enabled: false }
            }
            }, function(err, results) {
            if (err) throw err;
                resolve(results);
            });
        });
        let test = await result.then((res) => {
            return res;
        }).catch(err => {
            console.log(err);
        });

        console.log(test); 
        return test;
        }

    """)
    print(dimensions) # None
    return dimensions
asyncio.get_event_loop().run_until_complete(hmm())

注意:- 在任何网站中打开控制台并运行 js 脚本,然后返回一个对象/字典。

请建议解决此问题的方法。

4

1 回答 1

1

不确定您要完成什么,但如果您想从站点捕获响应,您应该听取响应。这是您网站的示例。它将打印出每个响应对象和相关信息。

import asyncio
from pyppeteer import launch

def interception_fun(response):
    # Response logic goes here
    print("URL:", response.url)
    print("Method:", response.request.method)
    print("Response headers:", response.headers)
    print("Request Headers:", response.request.headers)
    print("Response status:", response.status)
    return


async def hmm():
    browser = await launch(headless=False)
    page = await browser.newPage()
    await page.goto('https://jobs.chegg.com')
    page.on('response', interception_fun)
    
    await browser.close()

    return
asyncio.get_event_loop().run_until_complete(hmm())
于 2020-10-14T08:45:05.337 回答