Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ruby - Watir and the preceding_sibling method hmmm

Here is my code:

    #test
    require 'watir'


    url_file =
    "file:///home/alain/yo.html"
    # same as yo:

    yo =
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<div class="Time">time1</div>
<span class="Locus">locus1</span>
<span class="Locus">locus2</span>
<body text="andale">
  <div class="alpha">
    <div class="Time">time2</div>
    <span class="Locus">locus3</span>
    <div class="Time">time3</div>
  </div>
</body>
<span class="Locus_xxxx">locus4</span>
<span class="Locus">locus5</span>
<span class="Locus">locus6</span>
</html>'

    browser = Watir::Browser.new
    browser.goto url_file

    result = browser.spans(class: 'Locus_xxxx').map do |sp|
      time = sp.preceding_sibling(tag_name: 'body').text
      locus = sp.text
      "#{time} #{locus}"
    end

p result

And here the answer : ...timed out after 30 seconds, waiting for #"Locus_xxxx", :tag_name=>"span", :index=>0} --> {:tag_name=>"body", :adjacent=>:preceding, :index=>0}> to be located (Watir::Exception::UnknownObjectException)

Note that Justin Ko had the idea of preceding_sibling and map methods !! Common watir be friendly :) The idea here is to get the text from body tag : "andale". And this from the span tag with class= Locus_xxxx

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
#test
require 'watir'


url_file =
"file:///yo.html"
# same as yo:

yo =
'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<div class="Time">time1</div>
<span class="Locus_1">locus1</span>
<span class="Locus">locus2</span>
<span text="andale">
  <div class="alpha">
    <div class="Time">time2</div>
    <span class="Locus">locus3</span>
    <div class="Time_yyyy">time3</div>
  </div>
</span>
<span class="Locus_xxxx">locus4</span>
<span class="Locus">locus5</span>
<span class="Locus">locus6</span>
</html>
'

browser = Watir::Browser.new
browser.goto url_file

result = browser.divs(class: 'Time_yyyy').map do |dv|
  locus = dv.parent.parent.preceding_sibling(tag_name: 'span', class: 'Locus_1').text
  time = dv.text
  "#{time} #{locus}"
end

This works ! result is ["time3 locus1"] [Finished in 4.0s]

Topic related to this: Watir scraping sequential elements : so simple, but no


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...