2014-07-23 3 views
0

처음 2 개 요소 선택 :CSS 또는 XPath는 : 나는 Scrapy을 연습하고 질문 물어보고 싶은

내가 스크랩 할 웹 사이트는이 같은 구조를 가지고 :

<td class="c3"> 
    <div class="text"> 
     <a class="title" href="https:// ">movie</a> 
     <a href="https:/ ">movieEN</a> 
     <p><ins><a hpp="thisweek-guide" href="https:// ">see more</a></ins></p> 
    </div> 
</td> 

을하지만 난 단지 원하는 마지막 2 시간 href 요소 (영화 및 MovieEN) (더 자세히보기) 어떻게해야합니까?
여기 내 코드와 나는 2 가지 볼

ssel.css("td.c3 a:nth-child(-n+3)::text").extract()

답변

2

작동하지 않습니다

  • a:nth-child(-n+3)부모 요소의 처음 3 자녀를 선택할 것입니다. 귀하의 경우에는

는 3 개 a 요소를 선택합니다 : 처음 2 어린이 1 <div class="text">의 2이며, 마지막 하나는 내가 a:nth-child(-n+3)이 제대로 변환되지 않습니다 생각 <ins>

  • 의 첫번째 자식 N + B 형태의 음의 값 (scrapy 내부적 cssselect 사용)
cssselect하여 이 옵션을 선택합니다

:

>>> cssselect.HTMLTranslator().css_to_xpath('a:nth-child(-n+3)') 
u"descendant-or-self::*/*[name() = 'a' and ((position() -3) mod -1 = 0 and position() >= 3)]" 

그것은해야 뭔가

u"descendant-or-self::*/*[name() = 'a' and ((position() -3) mod -1 = 0 and position() <= 3)]"처럼 당신이 CSS 셀렉터와의 XPath의 조합을 사용하는 것이 좋습니다 (당신은 scrapy에서 그들을 체인 수) :

In [1]: import scrapy 

In [2]: selector = scrapy.Selector(text=""" 
    ...: <td class="c3"> 
    ...:  <div class="text"> 
    ...:   <a class="title" href="https:// ">movie</a> 
    ...:   <a href="https:/ ">movieEN</a> 
    ...:   <p><ins><a hpp="thisweek-guide" href="https:// ">see more</a></ins></p> 
    ...:  </div> 
    ...: </td>""") 

In [3]: selector.css("td.c3 a:nth-child(-n+3)::text").extract() 
Out[3]: [] 


In [4]: selector.css("td.c3").xpath("(.//a)[position() < last()]//text()").extract() 
Out[4]: [u'movie', u'movieEN'] 

In [5]: 

또는 경우 당신은 단지 <div class="text">의 아이들을 고려해야합니다 :

In [8]: selector.css("td.c3 > * > a::text").extract() 
Out[8]: [u'movie', u'movieEN'] 

In [9]: selector.css("td.c3 div.text > a::text").extract() 
Out[9]: [u'movie', u'movieEN'] 
관련 문제