2016-11-29 5 views
0

CSS 선택기가 올바른 정보를 반환하지만 XPath가 반환하지 않는 이유는 무엇입니까?.css가 XPath가 아닌이 Nokogiri 개체와 함께 작동하는 이유는 무엇입니까?

source = "<hgroup class='page-header channel post-head' data-channel='tech' data-section='sec0=tech&amp;sec1=index&amp;sec2='><h2>Tech</h2></hgroup>" 

doc = Nokogiri::HTML(source) 
doc.xpath('//hgroup[case_insensitive_equals(@class,"post-head")]//h2', XpathFunctions.new) 
=> [] 

doc.css("hgroup.post-head")[0].css("h2") 
=> [#<Nokogiri::XML::Element:0x6c2b824 name="h2" children=[#<Nokogiri::XML::Text:0x6c2b554 "Tech">]>] 

답변

1

class 속성이 post-head (소문자를 구별 여부의 경우) 동일하지 않습니다 때문입니다, case_insensitive_equals은 이름에서 알 수 무엇을 수행한다고 가정하지만, 을 포함 않습니다. XPath는 class 속성을 일반 문자열로 취급하지만 CSS를 분리 할 때 클래스를 개별적으로 처리하지는 않습니다. 일하는 것이

간단한 XPath는 다음과 같습니다

doc.xpath('//hgroup[contains(@class, "post-head")]//h2') 

(I 사용자 정의 기능을 제거했습니다, 당신은 소문자를 구별이 사건을 수행하는 직접 작성해야합니다.)

이 ISN ' 꽤 비슷하지만, 심지어는 not-post-head과 같은 클래스와 일치합니다. 더 완벽한 XPath는 something like this 일 것입니다 :

doc.xpath('//hgroup[contains(concat(" ", normalize-space(@class), " "), " post-head ")]//h2')