2014-02-17 4 views
2

댓글이 달린 태그에서 스크랩이있는 콘텐츠를 어떻게 추출 할 수 있습니까?Scrapy : 주석 처리 된 (숨겨진) 내용 추출

<div class="fruit"> 
    <div class="infos"> 
     <h2 class="Name">Banana</h2> 
     <span class="edible">Edible: Yes</span> 
    </div> 
    <!-- 
    <p class="color">Yellow</p> 
    --> 
</div> 

답변

4

당신은 코멘트 내용을 얻을 수 //comment() 같은 XPath 식을 사용할 수 있으며, 주석 태그를 제거 한 후 그 내용을 분석 :

예를 들어, 어떻게 다음 예에서 "노란색"를 추출 .

예 scrapy 쉘 세션 : 모든

[email protected]:~$ scrapy shell 
... 
In [1]: doc = """<div class="fruit"> 
    ...:  <div class="infos"> 
    ...:   <h2 class="Name">Banana</h2> 
    ...:   <span class="edible">Edible: Yes</span> 
    ...:  </div> 
    ...:  <!-- 
    ...:  <p class="color">Yellow</p> 
    ...:  --> 
    ...: </div>""" 

In [2]: from scrapy.selector import Selector 

In [4]: selector = Selector(text=doc, type="html") 

In [5]: import re 

In [6]: regex = re.compile(r'<!--(.*)-->', re.DOTALL) 

In [7]: selector.xpath('//comment()').re(regex) 
Out[7]: [u'\n <p class="color">Yellow</p>\n '] 

In [8]: comment = selector.xpath('//comment()').re(regex)[0] 

In [9]: commentsel = Selector(text=comment, type="html") 

In [10]: commentsel.css('p.color') 
Out[10]: [<Selector xpath=u"descendant-or-self::p[@class and contains(concat(' ', normalize-space(@class), ' '), ' color ')]" data=u'<p class="color">Yellow</p>'>] 

In [11]: commentsel.css('p.color').extract() 
Out[11]: [u'<p class="color">Yellow</p>'] 

In [12]: commentsel.css('p.color::text').extract() 
Out[12]: [u'Yellow'] 
+0

, 그것은 작동합니다. 하지만 HTML 페이지에서는 그렇지 않습니다. 'Line [8]'variable'comment = []'스켈레톤에 의해 코멘트가 보이지 않는 것처럼. – Matt

+0

예제 URL이 있습니까? –

+0

확실 : http://www.vietnamworks.com/it-software-jobs-i35-en 주석으로'' – Matt

0

먼저, 페이지에서 모든 의견을 얻기 위해 XPath는 아래 사용합니다.

data = response.xpath('//comment()').extract() 

이제 모든 키 값 ID를 사용하여 의미를 설명합니다.

up_data = [] 
for d in data: 
    if 'key' in d: 
     up_data.append(d) 

정의, 문자열에서

html_template = '<html><body>%s</body></html>' 
for up_d in up_data: 
    up_d = html_template % up_d.replace('<!--','').replace('-->', '') 
    sel = Selector(text=up_d) 
    sel.xpath('//div[@class="table_outer_container"]') 

    // DO what you want