python - 将 file_name 参数传递给管道以在 scrapy 中导出 csv

标签 python web-scraping scrapy scrapy-pipeline

我需要 scrapy 从命令行获取参数 (-a FILE_NAME="stuff") 并将其应用于在 pipelines.py 文件中的 CSVWriterPipeLine 中创建的文件。 (我使用 pipeline.py 的原因是内置的导出器在输出文件中重复数据和标题。相同的代码,但在管道中写入修复了它。)

我尝试从 scrapy.utils.project import get_project_settings 中看到

How to access scrapy settings from item Pipeline

但我无法从命令行更改文件名。

我也尝试过在页面上实现@avaleske 的解决方案,因为它专门解决了这个问题,但我不知道将他谈到的代码放在我的 scrapy 文件夹中的什么地方。

帮忙吗?

设置.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"

管道.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

蜘蛛.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

最佳答案

您可以使用“设置”概念和 -s 命令行参数:

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

关于python - 将 file_name 参数传递给管道以在 scrapy 中导出 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527080/

相关文章:

html - 使用 R 抓取带有图像、文本和空白单元格的维基百科 HTML 表格

django - 在 Celery 任务中运行 Scrapy 蜘蛛(django 项目)

python - Scrapy的这个正则表达式怎么写?

python - 没有名为 _gdal 的模块

python - 提取每个子列表的第一项

python - 如何使用 Selenium 提取标签内值属性的文本

python - 字典作为 Django 模板中的表

python - xpath不能只选择一个html标签

python - Scrapy不处理Xpath和CSS选择器中的TBODY

python - 当我按 CSS 类过滤时,为什么 scrapy 和 beautifulsoup 都没有返回任何内容?