How can I get some particular link form the links collection

流过昼夜 提交于 2019-12-13 04:37:52

问题


I'm using watir-webdriver have several lines of the same code shown below:

...
    <p class="schedule-text">
    by 
    <a href="http://www.somesite.com">MarketingClub</a> 
    in 
    <a href="http://www.somesite2.com">Marketing</a>     
    </p>

I need to get the first links included in p tag and the second links included in p tag so using page object I've added the following code:

links(:followees_category, :css => "#home-followees li.animate-in ul li[data-show-id] p.schedule-text a")

...

followees_category_elements.attribute("href")

the last row will give me both links : http://www.somesite2.com, http://www.somesite2.com Unfortunately, I can't indicate in css :last/:first etc.

the second link can be gotten by changing css to :

#home-followees li.animate-in ul li[data-show-id] p.schedule-text a + a

but how can I get just the first links from such blocks? Of course, I can get both links and work with every 2nd, but maybe there is an alternative solution?


回答1:


You can use the css nth-of-type pseudo class to get elements based on their index (or relative position).

For example, a:nth-of-type(1) can be used to return all links that are the first line of their parent:

links(:followees_category, :css => "p.schedule-text a:nth-of-type(1)")

For the second links, you can do a:nth-of-type(2). Note that it is 1-based index.

links(:followees_category, :css => "p.schedule-text a:nth-of-type(2)")

For the first link, you can also do a:first-of-type:

links(:followees_category, :css => "p.schedule-text a:first-of-type")

If the second link is always the last link, you can also do a:last-of-type:

links(:followees_category, :css => "p.schedule-text a:last-of-type")



回答2:


I would not recommend using css selectors like these, because they make your tests harder to read and more fragile.

But, whatever the selector is in the end, i would use Ruby's Enumerable methods to get the second links like this:

links.select.each_with_index {|_, i| i.odd? }


来源:https://stackoverflow.com/questions/18231878/how-can-i-get-some-particular-link-form-the-links-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!