我想從 url = https://www.lazada.sg/puma-singapore/?q=All-Products&from=wangpu&langFlag=en&pageTypeId=2獲取資料(“折扣”)
但得不到
function myFunction() {
const url = 'https://www.lazada.sg/puma-singapore/?q=All-Products&from=wangpu&langFlag=en&pageTypeId=2'
// parse the data
function getData(url) {
const fromText = '<span data-spm-anchor-id="a2o42.seller.list.i41.62ff63deVng91O">';
const toText = '</span>';
const content = UrlFetchApp.fetch(url).getContentText();
const scraped = Parser
.data(content)
.setLog()
.from(fromText)
.to(toText)
.build();
return scraped;
}
const discount = getData(url).replace("%", "").replace(/\-/g,"");
Logger.log(discount)
}
uj5u.com熱心網友回復:
當我看到 URL 的 HTML 時,似乎這些值是使用 Javascript 放置的。但是,幸運的是,這些值作為 JSON 資料包含在 HTML 中。因此,在這個答案中,我想建議通過決議 HTML 中的 JSON 資料來檢索值。示例腳本如下。
示例腳本:
請設定您要檢索的專案名稱的值discount。
function myFunction() {
const itemName = "PUMA Unisex Deck Backpack II"; // Please set the item name.
const url = 'https://www.lazada.sg/puma-singapore/?q=All-Products&from=wangpu&langFlag=en&pageTypeId=2'
const content = UrlFetchApp.fetch(url).getContentText();
const str = content.match(/window.pageData =([\w\s\S] ?});/);
if (!str || str.length < 1) return;
const obj = JSON.parse(str[1]);
const items = obj.mods.listItems.filter(({ name }) => name == itemName);
if (items.length == 0) return;
const res = items.map(({ discount }) => discount);
console.log(res)
}
測驗:
- 運行此腳本時,
[ '-34%', '-34%' ]將獲得。因為有 2 項PUMA Unisex Deck Backpack II。因此,結果有 2 個值。
筆記:
- 在當前階段,我可以確認此腳本有效。但是,如果將來改變 HTML 的結構,這個腳本可能無法使用。請注意這一點。
參考:
- JSON.parse()
- 篩選()
添加:
關于About your additional request of your comment of Thanks for the support However I want to get all the data of all products Is there any way?, you want the discount values of all items. Is my understanding correct?您的附加要求,
是的,我得到了所有折扣資料,但我得到了值“未定義”,我想在 MySheet 上獲取值形式“46”或“56”和 setValues。
在這種情況下,示例腳本如下。
示例腳本:
function myFunction() {
const url = 'https://www.lazada.sg/puma-singapore/?q=All-Products&from=wangpu&langFlag=en&pageTypeId=2'
const content = UrlFetchApp.fetch(url).getContentText();
const str = content.match(/window.pageData =([\w\s\S] ?});/);
if (!str || str.length < 1) return;
const obj = JSON.parse(str[1]);
const items = obj.mods.listItems;
if (items.length == 0) return;
const res = items.map(({ discount }) => [-parseInt(discount, 10) || 0]);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set the sheet name.
sheet.getRange(1, 1, res.length, res[0].length).setValues(res);
}
似乎當值為 時
discount,undefined產品沒有打折。所以在這種情況下,它是0%.而且,為了實作您想要檢索
-46%as值的目標46,我使用了-parseInt(discount, 10) || 0.運行此腳本時,檢索到的值將放入“Sheet1”的“A”列。不幸的是
i want get value form "46" or "56" and setValues on MySheet,我無法想象你的實際目標。因此,請根據您的實際目標修改此腳本。如果要檢索商品名稱和折扣值,請進行如下修改。
從
const res = items.map(({ discount }) => [-parseInt(discount, 10) || 0]);到
const res = items.map(({ name, discount }) => [name, -parseInt(discount, 10) || 0]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459903.html
