2011-12-13 68 views
0

我正在嘗試對我的網頁進行簡單的猴子測試,該測試會獲取頁面上的所有活動元素並以隨機順序單擊它們。獲取Webdriver中元素的所有屬性或xPath

當我這樣做,我想寫日誌就知道了,在這件我的測試點擊上測試墜毀

所以我想日誌文件看起來像這樣

01.01.11 11.01.01 Clicked on Element <span id='myspan' class ='myclass .....> 
01.01.11 11.01.01 Clicked on Element <span id='button' class ='myclass title = 'Button'.....> 

01.01.11 11.01.01 Clicked on Element //*[@id='myspan'] 
01.01.11 11.01.01 Clicked on Element //*[@id='button'] 

Webdriver + Ruby有什麼辦法嗎?

回答

1

我不認爲有一種方法,但你總是可以做這樣的事情(使用的Watir-的webdriver):

browser.divs.each do |div| 
    puts '<span ' + ['id','class','title'].map{|x| "#{x}='#{div.attribute_value(x)}'"}.join(' ') + '>' 
end 
+0

不,這不是。我只是通過例子來輸入這些元素。一些元素可能有'class'或'id'屬性,有些可能沒有 – ShockwaveNN

+1

我明白,但我認爲這是非常接近你會得到。 – pguardiario

1

的webdriver不提供這種類型的功能,你會得到頁面的源代碼,並做一些自己的解析 - 我用C#這樣做的HTML敏捷性包,你就需要找到一個類似圖書館的紅寶石(參見:Options for HTML scraping?

1

你可以這樣做:

  1. 獲取所有可點擊的元素 例如,查找所有鏈接,查找所有可點擊的跨度。把那些候選人名單

  2. 隨機挑選的候選名單

  3. 一個元素單擊非常元素,寫一些日誌

+0

你將如何獲得元素的XPath或其所有屬性? – Anders

+0

爲什麼使用XPath?在自動化方面,XPath是惡魔。我建議使用ID。即使是上課也比XPath更好 – maguschen

+0

XPath本身並不邪惡,但有時候人們使用它的方式非常糟糕。如果你知道如何使用它,它既強大又多才多藝(而且根本不脆),一旦你學會了它,就沒有回頭路了。 – Anders

1

我調整@ pguardiario的答案,想出這個方法:

def get_element_dom_info(@e) 
    if @e.class != Selenium::WebDriver::Element 
    raise "No valid element passed: #{@e.class}" 
    end 
    @attrs = ['id', 'class', 'title', 'href', 'src', 'type', 'name'] 
    return "<" + @e.tag_name + @attrs.map{ |x| " #{x}='#{@e.attribute(x)}'" if @e.attribute(x) && @e.attribute(x) != "" }.join('') + ">" 
end 

當然,希望你進入它的一個參數是一個實際的硒元素。此外,它不包含所有可能的屬性,但這是其中的大多數屬性(如果需要,您可以隨時添加額外的屬性)。

我想你可以通過一些像這樣的代碼,這個整合:

def clickElement(*args) 
    ... # parse vars 
    @e = @driver.find_element(...) 
    puts get_timestamp + " Clicked on Element: " + get_element_dom_info(@e) 
end 

UPDATE 最近,我意識到,我可以得到使用原生的JavaScript元素的完整的HTML(D'哦!)。你必須使用hack來獲得「outerHTML」。這是我的新方法:

def get_element_dom_info(how, what) 
    e = @driver.find_element(how, what) 

    # Use native javascript to return element dom info by creating a wrapper 
    # that the element node is cloned to and we check the innerHTML of the parent wrapper. 
    return @driver.execute_script("var f = document.createElement('div').appendChild(arguments[0].cloneNode(true)); return f.parentNode.innerHTML", e) 

end 
相關問題