Ruel Nopal
Ruel Nopal

Reputation: 415

How to use Conditional in Nokogiri

Is there a way to put No Url Foud in a blank or missing anchor tag. The reason of asking this is that the textnode output 50 textnode but the url only output 47 as some of the anchor is missin or not availble, causing the next list to colaps and completely ruin the list

see the screenshots td tag|Td list

I could get the textNode and the attributes the only problem here is some of the td list has a missing anchor causing the other list to collapse

<table>
    <tr>
        <td><a href="url">TextNode</a></td>
    </tr>
    <tr>
        <td><a href="url">TextNode</a></td>
    </tr>
    <tr>
        <td><a href="url">TextNode</a></td>
    </tr>
    <tr>
        <td>TextNode With No Anchor</td>
    </tr>    <tr>
        <td><a href="url">TextNode</a></td>
    </tr>
    <tr>
        <td>TextNode With No Anchor</td>
    </tr>
</table>
company_name = page.css("td:nth-child(2)")
company_name.each do |line|
    c_name = line.text.strip
    # this will output 50 titles
    puts c_name
end

directory_url = page.css("td:nth-child(1) a")
directory_url.each do |line|
    dir_url = line["href"]
    # this will output 47 Urls since some list has no anchor tag.
    puts dir_url
end

Upvotes: 0

Views: 94

Answers (1)

tadman
tadman

Reputation: 211600

You can't find things that aren't there. You have to find things that are there, and then search within them for elements that may or may not be present.

Like:

directory = page.css("td:nth-child(1)")
directory.each do |e|
  anchor = e.css('a')

  puts anchor.any? ? anchor[0]['href'] : '(No URL)'
end

Upvotes: 1

Related Questions