Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ruby - Accessing a div element in an array of li elements

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!!!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...