【问题标题】:Parsing data from html based on a string基于字符串从html解析数据
【发布时间】:2015-11-06 12:11:22
【问题描述】:

我需要从一个html页面中提取一个特定的值——相关的html内容如下:

-html --

<table border=0  cellspacing='1'  cellpadding='0' class="content-denote"     width="965" >
                        <tr height=17><td align=left class="text21"><b>Sensex : 26326.60
                                    [22.40]

                                    <img src="../images/arow_green.jpg" width="14" height="12">




                                    &nbsp;&nbsp;&nbsp; Nifty : 7970.05 [14.60]
                                    <img src="../images/arow_green.jpg" width="14" height="12">

-- end of html --

我需要提取的值是出现在 "Nifty :" 之后的值 - 在上面的 example '7970.05' 中。

我有以下代码来提取它:

--代码--

$('td.text21').each(function () {
                    status = true;
                    var price1 = $(this).text().substr(340,7);

--代码结束--

但有时我注意到该值的位置不是 340 - 它有时会更改为 303,因为 img src 链接会根据某些值而变化。

该值将始终位于“Nifty :”之后 - 这永远不会改变。

有没有一种方法可以编码以提取出现在“Nifty :”之后的 7 位数值

任何帮助将不胜感激。

【问题讨论】:

    标签: jquery html parsing cheerio


    【解决方案1】:

    您可以从“Nifty :”之后的位置获取子字符串,而不是从 340 获取子字符串,您可以这样做

    $(this).text().indexOf("Nifty :") + 7; // 7 is the length of "Nifty :"
    

    所以你的新行将是:

    var price1 = $(this).text().substr($(this).text().indexOf("Nifty :") + 7, 7);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2012-05-04
      • 2016-06-27
      • 2019-12-18
      • 2016-05-27
      相关资源
      最近更新 更多