Accessing a div element in an array of li elements

孤街醉人 提交于 2020-01-07 08:26:16

问题


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:


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


来源:https://stackoverflow.com/questions/10397787/accessing-a-div-element-in-an-array-of-li-elements

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