Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the all the href links of the page using ruby capybara

I'm having an issue getting the list of links of the pages and saving it as an array, so I can find out what links are used in the page

<ul class="test">   
 <li class="social_1"></li>
     <a href="link1"></a>   
 <li class="social_2"></li>
     <a href="link2"></a>   
 <li class="social_3"></li>
     <a href="link3"></a>   
 <li class="social_4"></li>
     <a href="link4"></a> 
</ul>

I tried using

list_items = page.all('li').collect(&:href)
puts list_items;

but it's not giving the correct answer.

im having this error

  undefined method `href' for #<Capybara::Element tag="li"> (NoMethodError)
like image 453
B_B Avatar asked Sep 14 '25 10:09

B_B


1 Answers

There are two issues:

  • The href attribute exist on the a element rather than the li element.
  • Elements do not have an href method. To get the attribute value use the [] method.

Depending on your preference, any of the following would work:

page.all('li').map { |li| li.find('a')['href'] }

page.all('li a').map { |a| a['href'] }

page.all('a').map { |a| a['href'] }
like image 182
Justin Ko Avatar answered Sep 17 '25 21:09

Justin Ko