2010-03-20 126 views
2

我需要從下面列出的html中提取實際的電話號碼,但我不確定如何使用Nokogiri CSS來做到這一點,因爲周圍沒有任何html標籤。當一個at_css(.phonetitle)它只解析電話而不是數字。解析沒有HTML標籤的數據

<div class="detail"> 
    <span class="address">Corner of Toorak Road and Chapel Street, South Yarra</span><br> 
    <span class="phonetitle">Phone</span> 95435 34341 
    <br><br> 
</div> 

回答

0

沒有一點點的XPath不能處理:

#!/usr/bin/env ruby 
require 'nokogiri' 

doc = Nokogiri::HTML(<<-HERE) 
    <div class="detail"> 
    <span class="address"> 
     Corner of Toorak Road and Chapel Street, South Yarra 
    </span><br> 
    <span class="phonetitle">Phone</span> 95435 34341 
    <br><br> 
    </div> 
HERE 

puts doc.search('*[@class="detail"]/text()').text.strip 
# => 95435 34341 
-1

這很容易解析,因爲電話號碼本身沒有明確的包裝。這不是它自己的或者。

如果你把整個東西都變成了javascript,我想你可以通過使用split()方法來分解它。

var string = '<div class="detail"> 
    <span class="address">Corner of Toorak Road and Chapel Street, South Yarra</span><br> 
    <span class="phonetitle">Phone</span> 95435 34341 
    <br><br> 
</div>'; 

var a = string.split('Phone</span>'); 
var b = string.split('<br>',a[1]); 
return b[0]; 
0

試試這個:

public static final int MAX_HTML_TAG_LENGTH = 10; 
public static final String[] REGEX_HTTP_TAG_FILTER = new String[] { 
      "[\\t\\n\\r\\f]+", 
      "<(s|S)(c|C)(r|R)(i|I)(p|P)(t|T)[^>]*>.+?</(s|S)(c|C)(r|R)(i|I)(p|P)(t|T)>", 
      "<(s|S)(t|T)(y|Y)(l|L)(e|E)[^>]*>.+?</(s|S)(t|T)(y|Y)(l|L)(e|E)>", 
      "<[a-zA-Z]{1," + MAX_HTML_TAG_LENGTH + "}\\s*[^>]*>", 
      "</[a-zA-Z]{1," + MAX_HTML_TAG_LENGTH + "}>", "<!--.+?-->", 
      "&nbsp;", 
      "[ ]{2,}+" 
}; 

for (int i = 0; i < REGEX_HTTP_TAG_FILTER.length; i++) { 
      result = result.replaceAll(REGEX_HTTP_TAG_FILTER[i], " "); 
} 
0

這裏的XPath表達式查找電話號碼:

*[@class='phonetitle']/following-sibling::text() 

例在Python中(你可以將它移植到Ruby和nokogiri使用@Jörg W Mittag's answer):

#!/usr/bin/env python 
from lxml import html 

doc = html.fromstring(""" 
    <div class="detail"> 
    <span class="address"> 
     Corner of Toorak Road and Chapel Street, South Yarra 
    </span><br> 
    <span class="phonetitle">Phone</span> 95435 34341 
    <br><br> 
    </div> 
""") 

pn, = doc.xpath("*[@class='phonetitle']/following-sibling::text()") 
print pn.strip() 
# -> 95435 34341