【问题标题】:Matlab text string/html parseMatlab 文本字符串/html 解析
【发布时间】:2014-04-08 09:56:39
【问题描述】:

我正在尝试将信息从网站 (html) 获取到 MATLAB。我可以使用以下方法将 html 从在线获取为字符串:

urlread('http://www.websiteNameHere.com...');

一旦我有了字符串,我就有了一个很长的字符串变量,它包含了整个 html 文件的内容。从这个变量中,我正在寻找非常具体的类中的值/字符。例如,html/website 会有一堆行,然后会有如下形式的感兴趣的类:

...
<h4 class="price">
 <span class="priceSort">$39,991</span>
</h4>
<div class="mileage">
 <span class="milesSort">19,570 mi.</span>
</div>
...
<h4 class="price">
 <span class="priceSort">$49,999</span>
</h4>
<div class="mileage">
 <span class="milesSort">9,000 mi.</span>
</div>
...

我需要能够获取&lt;span class="priceSort"&gt;&lt;/span&gt; 之间的信息;即上述示例中的 39,991 美元和 49,999 美元。解决此问题的最佳方法是什么?如果标签是特定的开头和结尾也相同(例如&lt;price&gt;&lt;/price&gt;),我就没有问题...

我还需要知道最可靠的方法,因为我也希望能够找到&lt;span class="milesSort"&gt; 和其他此类信息。谢谢!

【问题讨论】:

    标签: html regex matlab parsing urlread


    【解决方案1】:

    试试这个,让我们知道它是否适合你 -

    url_data = urlread('http://www.websiteNameHere.com...');
    
    start_string = '<span class="priceSort">'; %// For your next case, edit this to <span class="milesSort">
    stop_string = '</span>';
    
    N1 = numel(start_string);
    N2 = numel(stop_string);
    
    start_string_ind = strfind(url_data,start_string);
    for count1 = 1:numel(start_string_ind)
        relative_stop_string_ind = strfind(url_data(start_string_ind(count1)+N1:end),stop_string);
        string_found_start_ind = start_string_ind(count1)+N1;
        string_found = url_data(string_found_start_ind:string_found_start_ind+relative_stop_string_ind(1)-2);
        disp(string_found);
    end
    

    【讨论】:

      【解决方案2】:

      使用strsplit的简单解决方案

      s = urlread('http://www.websiteNameHere.com...');
      
      x = 'class="priceSort">'; %starting string x
      y = 'class="milesSort">'; %starting string y
      z = '</span>'; %ending string z
      
      s2 = strsplit(s,x); %split for starting string x
      s3 = strsplit(s,y); %split for starting string y
      
      result1 = cell(size(s2,2)-1,1); %create cell array 1
      result2 = cell(size(s3,2)-1,1); %create cell array 2
      
      %loop through values ignoring first value
      %(change ind=2:size(s2,2) to ind=1:size(s2,2) to see why)
      
      %starting string x loop
      for ind=2:size(s2,2)
          m = strsplit(s2{1,ind},z);
          result1{ind-1} = m{1,1};
      end
      
      %starting string y loop
      for ind=2:size(s3,2)
          m = strsplit(s3{1,ind},z);
          result2{ind-1} = m{1,1};
      end
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        • 2012-08-29
        • 1970-01-01
        • 2016-12-07
        • 1970-01-01
        • 2012-04-19
        • 2011-07-03
        相关资源
        最近更新 更多