Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ruby - Using Nokogiri to Split Content on BR tags

I have a snippet of code im trying to parse with nokogiri that looks like this:

<td class="j">
    <a title="title text1" href="http://link1.com">Link 1</a> (info1), Blah 1,<br>
    <a title="title text2" href="http://link2.com">Link 2</a> (info1), Blah 1,<br>
    <a title="title text2" href="http://link3.com">Link 3</a> (info2), Blah 1 Foo 2,<br>
</td>

I have access to the source of the td.j using something like this: data_items = doc.css("td.j")

My goal is to split each of those lines up into an array of hashes. The only logical splitting point i can see is to split on the BRs and then use some regex on the string.

I was wondering if there's a Better way to do this maybe using nokogiri only? Even if i could use nokogiri to suck out the 3 line items it would make things easier for me as i could just do some regex parsing on the .content result.

Not sure how to use Nokogiri to grab lines ending with br though -- should i be using xpaths? any direction is appreciated! thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure about the point of using an array of hashes, and without an example I can't suggest something. However, for splitting the text on <br> tags, I'd go about it this way:

require 'nokogiri'

doc = Nokogiri::HTML('<td class="j">
    <a title="title text1" href="http://link1.com">Link 1</a> (info1), Blah 1,<br>
    <a title="title text2" href="http://link2.com">Link 2</a> (info1), Blah 1,<br>
    <a title="title text2" href="http://link3.com">Link 3</a> (info2), Blah 1 Foo 2,<br>
</td>')

doc.search('br').each do |n|
  n.replace("
")
end
doc.at('tr.j').text.split("
") # => ["", "    Link 1 (info1), Blah 1,", "Link 2 (info1), Blah 1,", "Link 3 (info2), Blah 1 Foo 2,"]

This will get you closer to a hash:

Hash[*doc.at('td.j').text.split("
")[1 .. -1].map{ |t| t.strip.split(',')[0 .. 1] }.flatten] # => {"Link 1 (info1)"=>" Blah 1", "Link 2 (info1)"=>" Blah 1", "Link 3 (info2)"=>" Blah 1 Foo 2"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...