views:

131

answers:

4

Hi,

I need to extract the actual phone number form the html listed below, but I'm not really sure how to do it using Nokogiri CSS since there are no html tags around it. When an at_css(.phonetitle) it only parse Phone and not the number.

<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>
A: 

That's a very difficult thing to parse easily because there isn't a clear wrapper around the phone number itself. It's not in its own or .

If you got the whole thing into javascript, I suppose you could break it down by using the split() method.

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];
jeffkee
A: 

Nothing a little XPath can't handle:

#!/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
Jörg W Mittag
A: 

Try this:

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], " ");
}
Geln Yang
A: 

Here's XPath expression to find the phone number:

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

Example in Python (you can port it to Ruby and nokogiri using @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
J.F. Sebastian