2017-12-17 19 views
0

웹 크롤러 치료를 사용하고 데이터를 CSV 파일로로드하고 있습니다. 나는 xpath를 사용하고 있으며 for 루프에서 실수로 인해 발생했다고 생각되는 데이터를 올바르게로드하는 문제를 발견했습니다. 각 페이지에서 첫 번째 제목, 저자 및 인용문 만 추출하여 3 행 csv 파일로 만듭니다. 이것은 파이썬을 사용하는 나의 처음이며, 열거/zip 함수를 올바르게 구현하기 위해 고심하고 있습니다. 여기파이썬 - 페이지 당 한 번만 반복되는 긁힌 데이터를 생성하는 루프

import scrapy 
class MySpider(scrapy.Spider): 
name = 'test' 
custom_settings = { 
    'FEED_FORMAT': 'csv', 
    'FEED_URI': 'test.csv' 
} 
start_urls = [ 
    'http://quotes.toscrape.com/', 
    'http://quotes.toscrape.com/page/2/', 
    'http://quotes.toscrape.com/page/3/' 
] 
def parse(self, response): 
    titles = response.xpath("//div[contains(@class, 'col-md-4')]/h2/text()").extract() 
    authors = response.xpath("//small[contains(@class, 'author')]/text()").extract() 
    quotes = response.xpath("//div[contains(@class, 'quote')]/span[contains(@class, 'text')]/text()").extract() 
    for i, (title, author, quote) in enumerate(zip(titles, authors, quotes)): 
     yield {'index': i, 'title': title, 'author': author, 'quote': quote} 

답변

1

문제 ziptitles1 요소를 포함이 경우, 인수로서 건네 최소리스트와 같은 수의 요소를 생성하는, 그래서 대해 한번만 반복한다 정확한지.

당신은 모든 요소에 동일한 제목, 당신은 반복해야합니다 authorsquotes :

title = response.xpath("//div[contains(@class, 'col-md-4')]/h2/text()").extract_first() 
authors = response.xpath("//small[contains(@class, 'author')]/text()").extract() 
quotes = response.xpath("//div[contains(@class, 'quote')]/span[contains(@class, 'text')]/text()").extract() 
for i, (author, quote) in enumerate(zip(authors, quotes)): 
    yield {'index': i, 'title': title, 'author': author, 'quote': quote}