【发布时间】:2016-11-12 20:38:01
【问题描述】:
这是我第一次使用 scrapy,我正在尝试使用管道将我需要的信息放入 csv 文件中。一切似乎都运行良好,直到我尝试从多个页面中抓取并开始返回一个空白的 csv 文件。我认为问题出在蜘蛛身上(因为当我在那里进行更改时它停止正常工作),但我正在建立管道以防万一那里也有问题。
这是我的蜘蛛:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from indeed.items import IndeedItem
class IndeedSpider(CrawlSpider):
name = "indeed"
allowed_domains = ['www.indeed.com']
start_urls = [
'http://www.indeed.com/jobs?as_and=&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=all&st=&salary=&radius=50&l=19103&fromage=30&limit=10&sort=&psf=advsrch'
]
rules = (Rule(LinkExtractor(allow=('http://www.indeed.com/jobs?q=&l=19103&radius=50&fromage=30&start=.*'))), )
def parse_item(self, response):
for sel in response.xpath("//div[contains(@class, 'row ')]"):
items = []
jobs = sel.xpath('//a[contains(@data-tn-element, "jobTitle")]/text()').extract()
city = sel.xpath('//span[@class="location"]/text()').extract()
company = sel.xpath('//span[@class="company"]/text()').extract()
for j, c, co in zip(jobs, city, company):
position = IndeedItem()
position['jobs'] = j.strip()
position['city'] = c.strip()
position['company'] = co.strip()
items.append(position)
yield items
这是我的管道:
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exporters import CsvItemExporter
class IndeedPipeline(object):
def process_item(self, item, spider):
return item
class CsvExportPipeline(object):
def __init__(self):
dispatcher.connect(self.spider_opened, signals.spider_opened)
dispatcher.connect(self.spider_closed, signals.spider_closed)
self.files = {}
def spider_opened(self, spider):
file = open('%s_jobs.csv' % spider.name, 'w+b')
self.files[spider] = file
self.exporter = CsvItemExporter(file)
self.exporter.start_exporting()
def spider_closed(self, spider):
self.exporter.finish_exporting()
file = self.files.pop(spider)
file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
任何帮助将不胜感激。
【问题讨论】:
-
抓取完成时的统计数据是什么?它应该说有多少物品被刮掉了等等。也许你所有的物品都被丢弃了?
-
好的,它确实是
[scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)。所以这似乎是问题的一部分。 -
您的抓取确实存在问题。您通常调试它的方式是在解析函数的某处添加
inspect_response(response, self),并且在抓取期间,scrapy 将抛出一个 shell 模式,您可以使用它来检查response对象。即检查您的 xpath 是否找到任何东西。
标签: csv scrapy scrapy-spider scrapy-pipeline