代码之家  ›  专栏  ›  技术社区  ›  Newbie

用Cheerio洗劫雅虎财务汇总表

  •  1
  • Newbie  · 技术社区  · 1 年前

    我正试图从中抓取“1y Target Est,1140.21” Yahoo Finance Summary Table ,用红色标记。

    enter image description here

    我尝试过这个代码,但没有得到任何数据。检查标签,我看到“11140.21”在下面 <td class="Ta(end) Fw(600) Lh(14px)" data-test="ONE_YEAR_TARGET_PRICE-value">1,140.21</td> 。所以我认为这个代码应该有效,但没有。我应该更改什么?非常感谢。

    function test() {
    
      const url = 'https://finance.yahoo.com/quote/NVDA/'
      const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
      const $ = Cheerio.load(res);
      const targetPrice = $('td[data-test="ONE_YEAR_TARGET_PRICE-value"]').text().toString();
      console.log(targetPrice)
    }
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   ggorlen Hoàng Huy Khánh    1 年前

    我不确定你的选择器是从哪里来的(我在页面上根本看不到),但这对我很有用:

    function test() {
      const url = "<Your URL>";
      const response = UrlFetchApp.fetch(url);
      const $ = Cheerio.load(response.getContentText());
      const targetPrice = $('[data-field="targetMeanPrice"]').text();
      console.log(targetPrice); // => 1,140.21
    }
    

    如果像这样从HTML中提取失败 <script type="application/json" data-sveltekit-fetched data-url="..."> 您可以使用的标签。

    另请参阅 Parsing Yahoo finance data