You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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=&quot;s-item__price&quot;><!--F#f_0--><!--F#f_0--><span class=&quot;POSITIVE&quot;>([\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=&quot;clipped&quot;> - Mistborn: The Final Empire - Paperback By Sanderson, Brandon - VERY GOOD</span></span></a></div><div class=&quot;s-item__details clearfix&quot;><div class=&quot;s-item__detail s-item__detail--primary&quot;><span class=&quot;s-item__price&quot;><!--F#f_0--><!--F#f_0--><span class=&quot;POSITIVE&quot;>$5.00</span><!--F/--><!--F/--></span></div><span class=&quot;s-item__detail s-item__detail--secondary&quot;><span class=&quot;s-item__seller-info&quot;><span class=&quot;s-item__seller-info-text&quot;>gilsdorf (48) 100%</span></span></span>`

    const priceSpan = /<span class=&quot;s-item__price&quot;><!--F#f_0--><!--F#f_0--><span class=&quot;POSITIVE&quot;>([\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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:07:33