2012-06-22 2 views
13

일부 html을 분석하기 위해 Nokogiri를 사용하고 있습니다. 하지만, 노드의 원시 html을 얻는 방법을 모르겠습니다. 예를 들어, 주어진 :Nokogiri가 노드의 원시 html을 얻습니다.

<tr class="tableX"> 
    <td align="center"> 
    <font size="2"><a href="javascript:open('9746')">9746</a></font> 
    </td> 
    <td align="center"> 
    <font size="2">2012-06-26</font> 
    </td> 
</tr> 

나는이 XPath를 사용하는 경우 :

doc = Nokogiri::HTML(html) 

nodes = doc.search("//tr[@class='tablebX']") 

nodes.each do |node| 
    node.text # or node.content 
end 

node.textnode.content의 결과는 다음과 같습니다

9746 
2012-06-26 

내가 tr 안에 모든 원시 HTML을 좀하고 싶습니다 블록. 이 경우 :

<td align="center"> 
    <font size="2"><a href="javascript:open('9746')">9746</a></font> 
</td> 
<td align="center"> 
    <font size="2">2012-06-26</font> 
</td> 

어떻게해야할까요?

답변

14

사용 node.to_s, 아니면 그냥 node : 추가 전성 체크 HTML로

nodes = doc.search("//tr[@class='tablebX']") 
nodes.each do |node| 
    puts node.to_s 
    puts '-'*40 
end 

내가 할 (당신은, 중간에 다른 클래스의 tr으로, 배) :

<tr class="tableX"> 
<td align="center"> 
<font size="2"><a href="javascript:open('9746')">9746</a></font> 
      </td> 
      <td align="center"><font size="2">2012-06-26</font></td> 
</tr> 
---------------------------------------- 
<tr class="tableX"> 
<td align="center"> 
<font size="2"><a href="javascript:open('9746')">9746</a></font> 
      </td> 
      <td align="center"><font size="2">2012-06-26</font></td> 
</tr> 
---------------------------------------- 
2

올바른 방법은 .children입니다. 선택한 요소 내부의 모든 HTML을 반환합니다.

data = Nokogiri::HTML(html) 
data.css("tr.container").children 

이 HTML을 반환합니다 :

그래서이 코드를 갖는

<tr class="container"> 
    <td>value</td> 
</tr> 

을 그리고이 과정을 사용하여

<td>value</td> 

을 내 대답은 너무 늦기 생각하지만 그건입니다 정확한 코드가 필요합니다.

3

children.to_html을 추가 할 수 있습니다. 아래에서 해보십시오 :

doc = Nokogiri::HTML(html) 

nodes = doc.search("//tr[@class='tablebX']") 

nodes.each do |node| 
    node.children.to_html # or node.content 
end 

이 도움이 되었기를 바랍니다.

관련 문제