2017-07-31 9 views
1

各レコードのResponse.URLを繰り返します。Scrapy:以下Scrapyのcrawlspiderは、URLの出力(response.url)を除いて、正常に動作している

import scrapy 
from scrapy.spiders import CrawlSpider, Rule 
from scrapy.linkextractors import LinkExtractor 

class Spider2(CrawlSpider): 
    #name of the spider 
    name = 'newstl' 

    #list of allowed domains 
    allowed_domains = ['graphics.stltoday.com'] 

    #starting url for scraping 
    start_urls = ['http://graphics.stltoday.com/apps/payrolls/salaries/agencies/'] 

    rules = [ 
    Rule(LinkExtractor(
     allow=['/apps/payrolls/salaries/.*/$']), 
     callback='parse_item', 
     follow=True), 
    ] 

    #setting the location of the output csv file 
    custom_settings = { 
     'FEED_FORMAT' : "csv", 
     'FEED_URI' : 'tmp/stltoday1.csv' 
    } 

    def parse_item(self, response): 
     #Remove XML namespaces 
     response.selector.remove_namespaces() 

     #Extract article information 
     name = response.xpath('//th[@scope="row"]/text()').extract() 
     position = response.xpath('//th[@scope="row"]/following-sibling::*[1]/text()').extract() 
     salary = response.xpath('//th[@scope="row"]/following-sibling::*[2]/text()').extract() 
     hiredate = response.xpath('//th[@scope="row"]/following-sibling::*[3]/text()').extract() 
     url = response.url 

     for item in zip(name,position, salary, hiredate, url): 
      scraped_info = { 
       'url' : item[4], 
       'name' : item[0], 
       'position' : item[1], 
       'salary' : item[2], 
       'hiredate' : item[3] 
      } 
      yield scraped_info 
出力がでURLの1つの文字を表示している

CSVの各行各レコードのURL全体を繰り返す方法はありますか?

url = response.url 
for item in zip(name, position, salary, hiredate): 
    yield { 
     'url' : url, 
     'name' : item[0], 
     'position' : item[1], 
     'salary' : item[2], 
     'hiredate' : item[3] 
    } 

をそして、代わりに、ツリー全体を複数回通過するの、結果の行を反復処理し、各アイテムのコンテキストから必要な情報を取得する:あなたがurlをビュンすべきではない

答えて

2

、ちょうどそれを直接設定:

for row in response.xpath('//th[@scope="row"]'): 
    yield { 
     "url": url, 
     "name": row.xpath('./text()').extract_first(), 
     "position": row.xpath('./following-sibling::*[1]/text()').extract_first(), 
     "salary": row.xpath('./following-sibling::*[2]/text()').extract_first(), 
     "hiredate": row.xpath('./following-sibling::*[3]/text()').extract_first(), 
    } 
関連する問題