Accessing a div element in an array of li elements

2019-09-20 01:58发布

I am trying to access a div in an li array

<ul>
<li class="views-row views-row-1 views-row-odd views-row-first">
 <div class="news-item">
</li>
<li class="views-row views-row-2 views-row-even">
<li class="views-row views-row-3 views-row-odd">
 <div class="news-item">
  <div class="image">
  <div class="details with-image">
    <h2>
    <p class="standfirst">The best two-seat </p>
  <div class="meta">
    <div class="pub-date">26 April 2012</div>
    <div class="topic-bar clearfix">
       <div class="topic car_review">review</div>
</div>
</div>
</div>
</div>
</li>

I am trying to access the "div class="topic car_review">car review "and get its text. The reason I am specifically using that text is that, depending on what the text is it would enter specific steps.

Code that I am using is

@topic = @browser.li(:class => /views-row-#{x}/).div(:class,'news-item').div(:class,'details').div(:class,'meta').div(:class,/topic /).text

The script was working fine before and suddenly it has stopped working and is just not able to get the div(:class,'news-item').

The error message I get is

unable to locate element, using {:class=>"news-item", :tag_name=>"div"} (Watir::Exception::UnknownObjectException)

I tried div(:class => /news-/) but still its just not able to find that element

I am really stuck!!!

1条回答
等我变得足够好
2楼-- · 2019-09-20 02:25

I assume that when you are doing li(:class => /views-row-#{x}/), the x means you are iterating over all rows? If so, then your script will fail on the row-2 since it does not contain the news-item div (resulting in the error that you see).

If there is only one of these 'topic car_review' div tags, you can just do:

@topic = @browser.div(:class, 'topic car_review')

Update - Iterating over each LI:

If you need to iterate over each LI, then you could do:

@browser.lis.each do |li|
    @topic = li.div(:class, 'topic car_review').text
end
查看更多
登录 后发表回答