2016-08-14 35 views
2

我習慣於使用PHP的Simple HTML DOM Parser(SHDP)來訪問元素,但我現在使用的是與watir-webdriver的ruby,我想知道這是否可以取代SHDP的功能,只要訪問網頁上的元素。如何使用watir-webdriver遍歷DOM(子/姐妹)?

所以在SHDP我應該這樣做:

$ret = $html->find('div[id=foo]'); 

這與id=foodiv一切都實例的數組。哦,$html是指定網址的HTML源代碼。無論如何,所以後來我把它放在一個循環:

foreach($ret as $element) 
     echo $element->first_child()->first_child()->first_child()->first_child()->first_child()->first_child()->first_child()->plaintext . '<br>'; 

現在,在這裏,每個->first_child()是父divid=foo(請注意,我有七)一個孩子,然後我打印7日明文兒童。像這樣的東西

<div id="foo"> 
    <div ...> 
     <div ...> 
      <div ...> 
       <div ...> 
        <div ...> 
         <div ...> 
          <div ...>HAPPINESS</div> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div 
</div> 

會打印「HAPPINESS」。所以,我的問題是,如何使用watir-webdriver完成這項工作(如果可能的話)?

此外,一般多,我怎麼能得到的Watir-webdriver的SHDP的DOM穿越能力:

enter image description here

我問,因爲如果的Watir-webdriver的不能做到這一點,我要去必須找出一種方法,將watir-webdriver中的瀏覽器實例的源代碼傳遞給使用SHDP的PHP腳本並以此方式獲取,並以某種方式將其返回給相關信息的ruby ...

+0

文檔/參考將是偉大的。 – Forwarding

回答

2

的Watir實現:索引功能(零基):

browser.div(id: 'foo').divs   # children 
browser.div(id: 'foo').div(index: 6) # nth-child 
browser.div(id: 'foo').parent   # parent 
browser.div(id: 'foo').div   # first-child 
browser.div(id: 'foo').div(index: -1) # last-child 

next_siblingprevious_sibling目前不能實現,請評論在這裏,如果你認爲有必要爲您的代碼:https://github.com/watir/watir/pull/270

注意,一般來說,你應該更喜歡使用索引來使用集合,但這些也行:

browser.div(id: 'foo').divs.first 
browser.div(id: 'foo').divs.last 

平裝代碼示例(是否希望通過文本來選擇或獲得的文本?):

browser.li(text: /Paperback/) 
browser.td(class: "bucket").li 
browser.table(id: 'productDetailsTable').li 

我們過去也曾要求支持像直接孩子這樣的事情,而不是解析所有的後代:https://github.com/watir/watir/issues/329

我們正在積極研究如何改進即將發佈的Watir版本中的內容,所以如果這個解決方案不適合你,請發表你的理想語法的建議,以完成你想要的東西:https://github.com/watir/watir/issues,我們將看到我們如何支持它。

+0

請參閱titusfortner對David Shute的回答的評論。 – Forwarding

1

I不要相信有一個.child方法可以爲你做到這一點。如果你知道它總是會在結構7周孩子的div你可以做不雅

require 'watir-webdriver' 
@browser = Watir::Browser.new 
puts @browser.div(id: 'foo').div.div.div.div.div.div.div.text 

你總是可以抓住他們的集合,然後解決了最後一個,假設它是最後一個,最深的在堆棧。

puts @browser.div(id: 'foo').divs.last.text 

這樣做也行得通,但是假設頁面結構是絕對的。它也不等於上面的元素迭代。由於我不清楚這樣做的價值,所以我不太願意採取相同的代碼。

+0

如何訪問「Paperback:」文字?[https://gist.github.com/anonymous/b759255a19e5fbf298e36fe66320d092]? – Forwarding

+0

你會做'@ browser.table(id:'productDetailsTable')。tr.td。???'哪裏'???'我不知道如何處理兄弟姐妹。 – Forwarding

+0

@Forwarding - 如果你想直接支持兄弟姐妹,請在這裏點擊:https://github.com/watir/watir/pull/270 – titusfortner

1

也許我沒有完全給你你在做PHP的事情。但是,如果你知道七子的文本將是HAPPINESS,那麼你可以簡單地找到通過XPath的一個元素:

步驟:

Given(/^I click the div "(.*?)" xpath$/) do |div_xpath| 
    Watir::Wait.until { @browser.div(:xpath => div_xpath).exist? } 
         @browser.div(:xpath => div_xpath).click 
end 

特點:

Given I click the div "//div[@id='foo'][text()='HAPPINESS']" xpath 
+0

請儘量避免在Watir中使用XPath選擇器。 Watir API幾乎完全沒有必要,閱讀起來很糟糕。 :)如果你想匹配基於文本的元素,請使用:'@ browser.div(text:「HAPPINESS」)' – titusfortner