我正在嘗試使用Cheerio和 Google Apps 腳本從網頁中抓取非常小的資訊。
以下是我用來獲取它的代碼片段:
function LinkResult(){
var url ='https://pagespeed.web.dev/report?url=http://www.juicecoldpressed.com/';
var result = UrlFetchApp.fetch(url);
var content = Cheerio.load(result.getContentText())
var item = content(".tag").text()
Logger.log(item)
}
在我運行時,此代碼不會在變數中顯示任何輸出item。當然,我缺少一些東西,你能指導我嗎?謝謝你。
uj5u.com熱心網友回復:
問題和解決方法:
https://pagespeed.web.dev/report?url=http://www.juicecoldpressed.com/在這種情況下,我擔心使用and的 URL 可能無法直接實作您的目標Cheerio。因為從瀏覽器上獲取的 HTML 資料UrlFetchApp.fetch(url)與瀏覽器上的不同。而且,似乎該值是使用腳本計算的。
幸運的是,在您的情況下,我認為可以使用 PageSpeed Insights API 檢索您的值。在這個答案中,我想建議使用 PageSpeed Insights API 來實作您的目標。
用法:
1. 開始使用 PageSpeed Insights API。
請查看官方檔案以使用 PageSpeed Insights API。在這種情況下,需要使用您的 API 密鑰。并且,請在 API 控制臺啟用 PageSpeed Insights API。
2. 示例腳本。
function myFunction() {
const apiKey = "###"; // Please set your API key.
const url = "http://www.juicecoldpressed.com/"; // Please set URL.
const apiEndpoint = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?key=${apiKey}&url=${encodeURIComponent(url)}&category=performance`;
const strategy = ["desktop", "mobile"];
const res = UrlFetchApp.fetchAll(strategy.map(e => ({ url: `${apiEndpoint}&strategy=${e}`, muteHttpExceptions: true })));
const values = res.reduce((o, r, i) => {
if (r.getResponseCode() == 200) {
const obj = JSON.parse(r.getContentText());
o[strategy[i]] = obj.lighthouseResult.categories.performance.score * 100;
} else {
o[strategy[i]] = null;
}
return o;
}, {});
console.log(values);
}
3. 測驗。
{ desktop: ##, mobile: ## }運行此腳本時,您可以在日志中看到 的回傳值。和 的值(單位是%.)分別是桌面desktop和mobile移動設備的值。
參考:
- 開始使用 PageSpeed Insights API
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/492878.html
