簡體   English   中英

如何使用水豚和惡作劇檢索innertext?

[英]How to retrieve innertext using capybara and poltergeist?

我有這個簡單的HTML:

<div> Test <span> someting </span></div>

我怎樣才能只檢索div的innertext

使用text檢索div中的所有文本:

[1] pry(#<SandBox>)> first(:xpath, '//div').text
=> "Test someting"

在我的XPath查詢中使用text()導致以下錯誤:

[2] pry(#<SandBox>)> first(:xpath, '//div/text()')
Capybara::Poltergeist::BrowserError: There was an error inside the PhantomJS portion of Poltergeist. This is probably a bug, so please report it. 
TypeError: 'null' is not an object (evaluating 'window.getComputedStyle(element).display')

但是,使用與Nokogiri相同的XPath工作:

[3] pry(#<SandBox>)> Nokogiri::HTML(page.html).xpath('//div/text()').text
=> " Test "

有沒有辦法只使用水豚而不訴諸Nokogiri?

你可以隨時使用Nokogiri和open-uri。

require 'nokogiri'
require 'open-uri'

2.2.0 :021 > html = Nokogiri::HTML::DocumentFragment.parse('<div> Test <span> someting     </span></div>').child

 => #<Nokogiri::XML::Element:0x44a7082 name="div" children=[#<Nokogiri::XML::Text:0x44a63ee " Test ">, #<Nokogiri::XML::Element:0x44a62e0 name="span" children=[#<Nokogiri::XML::Text:0x44a3f04 " someting ">]>]> 

然后,您可以根據要抓取的內容對其執行操作。 所以對於標簽內的文字:

2.2.0 :072 > html.children.first

 => #<Nokogiri::XML::Text:0x45ea37c " Test "> 

2.2.0 :073 > html.children.first.text

=> " Test " 

要么

2.2.0 :215 > html.children.first.content

 => " Test "

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM