[英]How can I use jQuery with Puppeteer?
因此,我正在使用 Puppeteer(無頭瀏覽器)瀏覽網站,當我訪問該 url 時,如何加載 jQuery 以在我的 page.evaluate() 函數中使用它。
我現在只有一個 .js 文件,我正在運行下面的代碼。 它按預期轉到我的 URL,直到我在 page.evaluate() 上收到錯誤為止,因為它似乎沒有像我認為的那樣從第 7 行的代碼中加載 jQuery: await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
任何想法如何在這里正確加載 jQuery,以便我可以在我的 page.evaluate() 函數中使用 jQuery?
(async() => {
let url = "[website url I'm scraping]"
let browser = await puppeteer.launch({headless:false});
let page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle2'});
// code below doesn't seem to load jQuery, since I get an error in page.evaluate()
await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
await page.evaluate( () => {
// want to use jQuery here to do access DOM
var classes = $( "td:contains('Lec')")
classes = classes.not('.Comments')
classes = classes.not('.Pct100')
classes = Array.from(classes)
});
})();
你走在正確的道路上。
此外,我沒有看到您的evaluate
函數中使用了任何 jQuery 代碼。 沒有document.getElement
函數。
最好的方法是添加 jQuery 的本地副本以避免任何跨源錯誤。
可以在此處已回答的問題中找到更多詳細信息。
更新:我嘗試了一個小片段來測試 jquery。 puppeteer 版本是 10.4.0。
(async () => { const browser = await puppeteer.launch({headless:false}); const page = await browser.newPage(); await page.goto('https://google.com',{waitUntil: 'networkidle2'}); await page.addScriptTag({path: "jquery.js"}) await page.evaluate( () => { let wrapper = $(".L3eUgb"); wrapper.css("background-color","red"); }) await page.screenshot({path:"hello.png"}); await browser.close(); })();
截圖是
所以 jquery 代碼肯定是有效的。
還要檢查主機網站是否已經沒有 jQuery 實例。 在這種情況下,您需要使用 jquery noConflict
$.noConflict();
修復!
我意識到在轉到我的初始 URL 后,我忘記包含在其中執行一些額外導航點擊的代碼,因此問題在於將腳本標記添加到我的初始 URL 而不是在導航到我的最終目標 URL 之后。
我還需要使用
await page.waitForNavigation({waitUntil: 'networkidle2'})
添加腳本標記之前,以便在添加腳本之前完全加載頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.