Google Apps Script正则匹配小文本正常,大文件返回null
eBay价格爬虫Google Apps Script正则匹配问题
我正在为Google Sheets编写基于Google Apps Script的简易eBay价格爬虫函数,遇到了正则匹配异常的问题:
第一段代码(返回null,不符合预期)
// 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; }
上述正则表达式在regex101测试时完全正常,但运行代码匹配完整HTML文件时,htmlStr.match(priceSpan)返回null,无法获取目标span的所有匹配项。
第二段代码(可正常运行)
// 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; }
使用HTML片段测试时,正则匹配可得到正确结果,因此我认为正则表达式本身无问题。我对Google Apps Script和网页解析的了解有限,可能操作有误,恳请提供解决思路。
补充说明
- 尝试过使用更简单的正则
s-item__price,可以匹配到所有实例,但只要在正则中添加引号(转义或不转义),匹配就会失败。
内容的提问来源于stack exchange,提问作者Nebulous39
相关产品推荐
相关产品推荐

