我正在try 在Apps脚本中创建一个简单的eBay价格刮擦函数,用于Google Sheet:
// This code produces a null result (not correct)
function GetEbayPriceByISBN(isbn = 9780765377135)
{
const ebayUrl = 'https://www.ebay.com/sch/i.html?_nkw=' + isbn + '&_sacat=0&LH_TitleDesc=0&_odkw=' + isbn + '&LH_Complete=1&LH_Sold=1'
let response = UrlFetchApp.fetch(ebayUrl)
let htmlStr = response.getContentText()
const priceSpan = /<span class="s-item__price"><!--F#f_0--><!--F#f_0--><span class="POSITIVE">([\s\S]*?)<!--F\/--><!--F\/--><\/span>/gm;
let allPrices = htmlStr.match(priceSpan)
console.log(allPrices)
return allPrices;
}
上面的正则表达式是我能想出的最好的方法来获取我需要的准确数据.它完美地工作在here%,但当我运行代码时,它是fails.在与整个HTML文件进行匹配时,我得到的结果是从xmlStr.match(priceSpan)
开始为NULL,而实际上它应该给出该范围内出现的所有事件的列表.
但是,在对较小的HTML文件片段进行测试时,我确实得到了correct的结果:
// This code WORKS
function GetEbayPriceByISBN2(isbn = 9780765377135)
{
const testText = `</span><span class="clipped"> - Mistborn: The Final Empire - Paperback By Sanderson, Brandon - VERY GOOD</span></span></a></div><div class="s-item__details clearfix"><div class="s-item__detail s-item__detail--primary"><span class="s-item__price"><!--F#f_0--><!--F#f_0--><span class="POSITIVE">$5.00</span><!--F/--><!--F/--></span></div><span class="s-item__detail s-item__detail--secondary"><span class="s-item__seller-info"><span class="s-item__seller-info-text">gilsdorf (48) 100%</span></span></span>`
const priceSpan = /<span class="s-item__price"><!--F#f_0--><!--F#f_0--><span class="POSITIVE">([\s\S]*?)<!--F\/--><!--F\/--><\/span>/gm;
let allPrices = testText.match(priceSpan)
console.log(allPrices)
return allPrices;
}
所以我不认为regex有什么问题.我对Apps脚本和网页解析的了解很少,所以我可能做了完全错误的事情.
有什么好主意吗?谢谢.
Note:我试过使用更简单的正则表达式s-item__price
和这个does work(它可以找到‘S-ITEM__PRICE’的所有实例),但是一旦我向我的正则表达式添加报价(不管是否转义),它就失败了.