python - scrapy中是否可以动态创建管道?

标签 python scrapy

我有一个将数据发布到 webhook 的管道。我想将它重新用于另一只蜘蛛。我的管道是这样的:

class Poster(object):
    def process_item(self, item, spider):
        item_attrs = {
          "url": item['url'], "price": item['price'],
          "description": item['description'], "title": item['title']
        }

        data = json.dumps({"events": [item_attrs]})

        poster = requests.post(
            "http://localhost:3000/users/1/web_requests/69/supersecretstring",
            data = data, headers = {'content-type': 'application/json'}
        )

        if poster.status_code != 200:
            raise DropItem("error posting event %s code=%s" % (item, poster.status_code))

        return item

问题是,在另一个蜘蛛中,我需要发布到另一个网址,并可能使用不同的属性。是否可以指定而不是这样:

class Spider(scrapy.Spider):
    name = "products"
    start_urls = (
        'some_url',
    )
    custom_settings = {
        'ITEM_PIPELINES': {
           'spider.pipelines.Poster': 300,
        },
    }

类似于:

    custom_settings = {
        'ITEM_PIPELINES': {
           spider.pipelines.Poster(some_other_url, some_attributes): 300,
        },
    }

我知道创建蜘蛛时需要的 URL,以及要提取的字段。

最佳答案

执行此操作的方法很少,但最简单的方法是在管道中使用 open_spider(self, Spider)

用例示例:

scrapy 抓取 myspider -a pipeline_count=123

然后设置您的管道来读取此内容:

class MyPipeline(object):
    count = None

    def open_spider(self, spider):
        count = getattr(spider, 'pipeline_count')
        self.count = int(count)

    # or as starrify pointed out in the comment below
    # access it directly in process_item
    def process_item(self, item, spider):
        count = getattr(spider, 'pipeline_count')
        item['count'] = count
        return item
    <...>

关于python - scrapy中是否可以动态创建管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561735/

相关文章:

python - 502 Bad Gateway upstream 在使用 flask、uWSGI、nginx 从上游读取响应 header 时过早关闭连接

python - 在 pypdf2 中使用 PdfFileMerger() 后的页数

python - 为什么 pysftp 库中的 chdir 不影响 pysftp 库中的执行?

python - 防止在 ipython shell 中显示调试日志信息

python - 如何在 Pandas 的 .csv 文件中写入 DataFrame 时删除索引列?

python - 让 python 生成器在后台运行

python-2.7 - Scrapy 和 Selenium StaleElementReferenceException

python - 如何提取抓取图像的文件修改时间?

python - Scrapy使用FormRequest.from_response将pdf文件上传到特定表单(id)

python - 使用 Python 规范化空格