我需要scrapy从命令行获取参数(-a FILE_NAME =“stuff”)并将其应用于在pipelines.py文件中的CSVWriterPipeLine中创建的文件。 (我使用pipeline.py的原因是内置导出器重复数据并在输出文件中重复标题。相同的代码,但在管道中写入修复它。)
我尝试从scrapy.utils.project导入get_project_settings,如
中所示How to access scrapy settings from item Pipeline
但我无法从命令行更改文件名。
我也尝试在页面上实现@ avaleske的解决方案,因为它专门解决了这个问题,但我不知道在scrapy文件夹中将他所说的代码放在哪里。
帮助?
settings.py:
BOT_NAME = 'internal_links'
SPIDER_MODULES = ['internal_links.spiders']
NEWSPIDER_MODULE = 'internal_links.spiders'
CLOSESPIDER_PAGECOUNT = 100
ITEM_PIPELINES = ['internal_links.pipelines.CsvWriterPipeline']
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'internal_links (+http://www.mycompany.com)'
FILE_NAME = "mytestfilename"
pipelines.py:
import csv
class CsvWriterPipeline(object):
def __init__(self, file_name):
header = ["URL"]
self.file_name = file_name
self.csvwriter = csv.writer(open(self.file_name, 'wb'))
self.csvwriter.writerow(header)
def process_item(self, item, internallinkspider):
# build your row to export, then export the row
row = [item['url']]
self.csvwriter.writerow(row)
return item
spider.py:
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from internal_links.items import MyItem
class MySpider(CrawlSpider):
name = 'internallinkspider'
allowed_domains = ['angieslist.com']
start_urls = ['http://www.angieslist.com']
rules = (Rule(SgmlLinkExtractor(), callback='parse_url', follow=True), )
def parse_url(self, response):
item = MyItem()
item['url'] = response.url
return item
答案 0 :(得分:4)
您可以使用"设置"概念和scrapy crawl internallinkspider -s FILE_NAME="stuff"
命令行参数:
import csv
class CsvWriterPipeline(object):
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
file_name = settings.get("FILE_NAME")
return cls(file_name)
def __init__(self, file_name):
header = ["URL"]
self.csvwriter = csv.writer(open(file_name, 'wb'))
self.csvwriter.writerow(header)
def process_item(self, item, internallinkspider):
# build your row to export, then export the row
row = [item['url']]
self.csvwriter.writerow(row)
return item
然后,在管道中:
body {
top: 5rem;
right: 5rem;
bottom: 5rem;
left: 5rem;
position: absolute;
}