Watir and the preceding_sibling method hmmm

不打扰是莪最后的温柔 提交于 2019-12-13 11:02:36

问题


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


回答1:


#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



来源:https://stackoverflow.com/questions/51336385/watir-and-the-preceding-sibling-method-hmmm

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