2010-11-01 85 views
57

我正在寫一個黃瓜測試,我想在元素中獲取HTML。如何在使用水豚的元素中獲取HTML?

例如:

within 'table' do 
    # this works 
    find('//tr[2]//td[7]').text.should == "these are the comments" 

    # I want something like this (there is no "html" method) 
    find('//tr[2]//td[7]').html.should == "these are the <b>comments</b>" 
end 

任何人都知道如何做到這一點?

回答

0

好,水豚採用引入nokogiri解析,所以這個頁面可能是適當的:

http://nokogiri.org/Nokogiri/XML/Node.html

我相信content是你正在尋找的方法。

+0

沒有評論方法...試圖做到這一點:'find('// tr [2] // td [10]')。content' – 2010-11-05 12:32:07

+0

你可以發佈你的實際步驟嗎?看看你在這裏做什麼會很有幫助。我已經完成了page.find(...)並提到了Nokogiri文檔來解析響應。也許我只是幸運......請注意,我說page.find。我認爲Capybara提供了Webrat提供響應對象的頁面對象。 – 2010-11-05 17:28:57

+0

該步驟的內容位於原始文章中。 – 2010-11-12 14:38:25

1

嘗試調用它find('//tr[2]//td[10]').node獲得在實際引入nokogiri對象

23

這篇文章是老了,但我想我找到了一種方法,如果你還需要這一點。

訪問從水豚元素引入nokogiri節點(使用水豚1.0.0beta1,引入nokogiri 1.4.4)試試這個:

elem = find('//tr[2]//td[10]') 
node = elem.native 
#This will give you a Nokogiri XML element 

node.children[1].attributes["href"].value.should == "these are the <b>comments</b>" 

最後一部分可以爲你改變,但你應該能夠找到在該節點變量中的某個地方的HTML

+2

請注意,這隻適用於RackTest – 2013-02-14 17:50:08

+0

使用硒,這個答案不適用於我,但[這一個](http://stackoverflow.com/a/15439366/199712)。 – 2016-09-27 19:39:56

14

在我的環境中,find返回一個Capybara :: Element,它響應上面Eric Hu提到的native方法,它返回一個Selenium :: WebDriver :: Element(對於我) 。然後:文本獲取內容,因此它可以如此簡單:

results = find(:xpath, "//td[@id='#{cell_id}']") 
contents = results.native.text 

如果您正在查找表格單元格的內容。在Capybara :: Element中沒有內容,inner_html,inner_text或節點方法。假設人們不只是在製作東西,也許你會找到與發現不同的東西,具體取決於你是否加載了水豚。

4

大多數其他答案只適用於Racktest(因爲他們使用Racktest特有的功能)。

如果驅動程序支持JavaScript的評估(如硒),可以使用innerHTML

html = page.evaluate_script("document.getElementById('my_id').innerHTML") 
7

貌似可以做(node).native.inner_html獲得HTML內容,例如用HTML這樣的:

<div><strong>Some</strong> HTML</div> 

你可以做到以下幾點:

find('div').native.inner_html 
=> '<strong>Some</strong> HTML' 
+7

不適合所有人未定義的方法inner_html爲#<水豚:: Poltergeist ::節點:0x007ff9aa8c59a0>' – 2016-09-23 17:43:17

31

您可以撥打HTML DOM innerHTML物業:

find('//tr[2]//td[7]')['innerHTML'] 

應該對任何瀏覽器或驅動程序。 你可以,如果你使用的騷靈驅動程序檢查w3schools

+0

這也適用於硒鉻金屬。 – nruth 2016-02-23 16:26:54

+6

也和'poltergeist'一起工作。 – 2016-05-06 19:02:45

0

您也可以切換到capybara-ui並執行以下操作:

# define your widget, in this case in your role 
class User < Capybara::UI::Role 
    widget :seventh_cell, [:xpath, '//tr[2]//td[7]'] 
end 

# then in your tests 
role = User.new 

expect(role.widget(:seventh_cell).html).to eq(<h1>My html</h1>)