2017-05-17 2 views
1

URL의 웹 페이지에서 장 제목과 부제목을 추출하려고합니다. 이것은 내가 내가 최대로 결과를 얻을 어떻게 내 CSV정규화 된 공간이 치료에서 작동하지 않습니다.

content_item,full_url,title 
" 

     ,Chapter 1, 



     , 


    , 

     ,Instructor Introduction, 

     ,00:01:00, 



    , 

    , 

     ,Course Overview, 

을에서 다음과 같은 결과를 얻을 공백을 제거 내 XPath는의 정규화 fucntion를 사용하더라도 내 거미

import scrapy 
from ..items import ContentsPageSFBItem 

class BasicSpider(scrapy.Spider): 
    name = "contentspage_sfb" 
    #allowed_domains = ["web"] 
    start_urls = [ 
     'https://www.safaribooksonline.com/library/view/shell-programming-in/9780134496696/', 
    ] 

    def parse(self, response): 
      item = ContentsPageSFBItem() 
      item['content_item'] = response.xpath('normalize-space(//ol[@class="detail-toc"]//*/text())').extract(); 
      length = len(response.xpath('//ol[@class="detail-toc"]//*/text()').extract()); #extract() 
      full_url_list = list(); 
      title_list = list(); 
      for i in range(1,length+1): 
       full_url_list.append(response.url) 
      item["full_url"] = full_url_list 
      title = response.xpath('//title[1]/text()').extract(); 
      for j in range(1,length+1): 
       title_list.append(title) 
      item["title"] = title_list 
      return item 

입니다 각 항목 다음에 한 줄만 추가 하시겠습니까? 당신은 당신이 item['content_item']에서 XPath 식을 변경해야 Table of Contents 섹션 내의 모든 텍스트를 원한다면

+0

을 출력해야합니까? '목차'안에있는 모든 텍스트를 긁어 내고 싶습니까? 코드의 페이지에는 CSV 파일의 '강사 소개'텍스트 및 기타 텍스트가 없습니다. – vold

+0

예 목차 –

+0

[scrapy shell] (https://doc.scrapy.org/en/latest/topics/shell.html)을 사용하는 것이 좋습니다. 스파이더 코드를 테스트하고 디버깅하는 데 매우 유용한 도구입니다 . xpath 선택기를 테스트하고 리턴하는 내용을 볼 수 있습니다. 예를 들어, item [ "title"]'은 동일한 문자열을 포함하는리스트를 반환합니다. 'item [ "title"]'과'item [ "full_url"]'에서 예상되는 결과가 무엇인지 지정할 수 있습니까? – vold

답변

1

:

item['content_item'] = response.xpath('//ol[@class="detail-toc"]//a/text()').extract() 

을 당신은 당신과 같은 코드 거미 다시 작성할 수 있습니다 : 당신의 예상 무엇

import scrapy 

class BasicSpider(scrapy.Spider): 

    name = "contentspage_sfb" 
    start_urls = [ 
     'https://www.safaribooksonline.com/library/view/shell-programming-in/9780134496696/', 
    ] 

    def parse(self, response): 
     item = dict()  # change dict to your scrapy item 
     for link in response.xpath('//ol[@class="detail-toc"]//a'): 
      item['link_text'] = link.xpath('text()').extract_first() 
      item['link_url'] = response.urljoin(link.xpath('@href').extract_first()) 
      yield item 

# Output: 
{'link_text': 'About This E-Book', 'link_url': 'https://www.safaribooksonline.com/library/view/shell-programming-in/9780134496696/pref00.html#pref00'} 
{'link_text': 'Title Page', 'link_url': 'https://www.safaribooksonline.com/library/view/shell-programming-in/9780134496696/title.html#title'} 
+0

여전히 제목 사이에 공백이 있습니다. –

+0

이상 하네. scrapy shell에서 xpath 표현식을 테스트 해 보셨습니까? 'response.xpath ('// ol [@ class = "detail-toc"] // a/text()')를 실행하면 어떤 결과가 나옵니까? [출력] (http://icecream.me/24349dd3e159e2847f398c7a1ea0ea3a) – vold

+0

작동합니다. 내 CSV에 넣으면 공백이 생깁니다 –