2011-09-21 2 views
0

내가 검색 한 내가 성공적으로처럼 보이는 HTML 테이블을 분석 한 것처럼 바로 지금 작동하는 데이터 스크레이퍼를 얻으려고 노력하고 것 같다 3 일 수색 이 :와 HTML 테이블 구문 분석 후 적절한 값을 얻는 방법 루비/노코 기리

<tr class='ds'> 
<td class='ds'>Length:</td> 
<td class='ds'>1/8"</td> 
</tr> 
<tr class='ds'> 
<td class='ds'>Width:</td> 
<td class='ds'>3/4"</td> 
</tr> 
<tr class='ds'> 
<td class='ds'>Color:</td> 
<td class='ds'>Red</td> 
</tr> 

그러나 저는 CSV로 정확하게 인쇄 할 수없는 것 같습니다.

Specifications = { 
:length => ['Length:','length','Length'],  
:width => ['width:','width','Width','Width:'], 
:Color => ['Color:','color'], 
....... 
}.freeze 

def specifications 
    @specifications ||= xml.css('tr.ds').map{|row| row.css('td.ds').map{|cell| cell.children.to_s } }.map{|record| 
    specification = Specifications.detect{|key, value| value.include? record.first } 
    [specification.to_s.titleize, record.last] } 
end 

그리고 CSV는 (전체 배열로 보이는) 하나 개의 컬럼에 인쇄되어 다음과 같이

루비 코드는

[["", nil], ["[:finishtype, [\"finish\", \"finish type:\", \"finish type\", \"finish type\", \"finish type:\"]]", "Metal"], ["", "1/4\""], ["[:length, [\"length:\", \"length\", \"length\"]]", "18\""], ["[:width, [\"width:\", \"width\", \"width\", \"width:\"]]", "1/2\""], ["[:styletype, [\"style:\", \"style\", \"style:\", \"style\"]]"........ 

나는 문제가 믿는 I 반환 할 값을 지정하지 않았지만 출력을 지정하려고 할 때마다 성공하지 못했습니다. 어떤 도움이라도 대단히 감사하겠습니다!

+1

예상되는 출력은 무엇인가 : 당신이 속성이 Specification에 일치하지 않는하여 발생할 경우

, 당신은 단지로 변경하여 값을 드롭 수 있을까? –

답변

0

시도 변경

[specification.to_s.titleize, record.last] 

[specification.last.first.titleize, record.last] 

하는 detect 예컨대 수득 to_s에 의해 "[:length, [\"Length:\", \"length\", \"Length\"]]" 될 것 [:length, ["Length:", "length", "Length"]]. last.first을 사용하면 "Length:" 부분 만 추출 할 수 있습니다.

xml.css('tr.ds').map{|row| row.css('td.ds').map{|cell| cell.children.to_s } }.map{|record| 
     specification = Specifications.detect{|key, value| value.include? record.first } 
     [specification.last.first.titleize, record.last] if specification 
    }.compact 
+0

답장을 보내 주셔서 감사합니다. 나는 그 비틀기를 시험해 보았다. 그리고 그것은 나에게 뒤로 침을 뱉었다 : 레이크는 낙심했다! 무기 호에 대한 정의되지 않은 메서드'마지막 : 당신이 Specifications''에 맞지 않는 HTML 데이터가있는 경우 NilClass – Sky

+0

이 발생 (아무 키도 detect''에 의해 발견되지 않을 때를, 당신은 nil''있어요). 앞의 코드는'nil'을 행복하게 문자열로 변환하고''[ "", nil] "'을 얻었습니다. 문제는 그 경우에 무엇을보고 싶습니까? –

+0

나는이 도움이되는지 확실하지 오전하지만 난 (csv로에 대한) 루비 텍스트의 끝 부분이 있습니다 # 형식 = #의 CSV 헤더 필드 : FIELD_NAME => DEFAULTVALUE F = {ITEM_NAME을 => 전무, : 길이 => 전무는 : 폭 => 무기 호 : 입력 => 전무, ...}는 내가이 CSV – Sky