Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Merge branch 'master' into allow-customizing-export-column-names

Adrián Chavesf9c63384c0ad
diff --cc docs/topics/exporters.rst
index c20eac771,e5c99e5b1..43296f36f
--- a/docs/topics/exporters.rst
+++ b/docs/topics/exporters.rst
@@@ -192,33 -195,17 +195,33 @@@ BaseItemExporte
.. attribute:: fields_to_export
- A list with the name of the fields that will be exported, or ``None`` if
- you want to export all fields. Defaults to ``None``.
+ Fields to export, their order [1]_ and their output names.
- Some exporters (like :class:`CsvItemExporter`) respect the order of the
- fields defined in this attribute.
+ Possible values are:
- When using :ref:`item objects <item-types>` that do not expose all their
- possible fields, exporters that do not support exporting a different
- subset of fields per item will only export the fields found in the first
- item exported. Use ``fields_to_export`` to define all the fields to be
- exported.
+ - ``None`` (all fields [2]_, default)
+
+ - A list of fields::
+
+ ['field1', 'field2']
+
+ - A dict [3]_ where keys are fields and values are output names::
+
+ {'field1': 'Field 1', 'field2': 'Field 2'}
+
+ .. [1] Not all exporters respect the specified field order.
- .. [2] If you yield items as dicts (not :class:`Item` instances),
- exporters that need to know the fields to export beforehand, like
- :class:`CsvItemExporter`, only export the fields found in the
- first item.
++ .. [2] When using :ref:`item objects <item-types>` that do not expose
++ all their possible fields, exporters that do not support exporting
++ a different subset of fields per item will only export the fields
++ found in the first item exported.
+ .. [3] Dicts preserve insertion order since `Python 3.7`_
+ (`CPython 3.6`_, `PyPy 2.5`_). If you are using an older version
+ of Python, use an OrderedDict_ to enforce a specific field order.
+
+ .. _Python 3.7: https://docs.python.org/whatsnew/3.7.html
+ .. _CPython 3.6: https://docs.python.org/whatsnew/3.6.html#new-dict-implementation
+ .. _PyPy 2.5: https://morepypy.blogspot.com/2015/02/pypy-250-released.html
+ .. _OrderedDict: https://docs.python.org/library/collections.html#collections.OrderedDict
.. attribute:: export_empty_fields
@@@ -309,12 -296,12 +312,12 @@@ XmlItemExporte
CsvItemExporter
---------------
- .. class:: CsvItemExporter(file, include_headers_line=True, join_multivalued=',', \**kwargs)
+ .. class:: CsvItemExporter(file, include_headers_line=True, join_multivalued=',', **kwargs)
- Exports Items in CSV format to the given file-like object. If the
+ Exports items in CSV format to the given file-like object. If the
:attr:`fields_to_export` attribute is set, it will be used to define the
- CSV columns and their order. The :attr:`export_empty_fields` attribute has
- no effect on this exporter.
+ CSV columns, their order and their column names. The
+ :attr:`export_empty_fields` attribute has no effect on this exporter.
:param file: the file-like object to use for exporting the data. Its ``write`` method should
accept ``bytes`` (a disk file opened in binary mode, a ``io.BytesIO`` object, etc)
diff --cc scrapy/exporters.py
index b1c3bb698,712572673..5e36c3a96
--- a/scrapy/exporters.py
+++ b/scrapy/exporters.py
@@@ -2,19 -2,20 +2,21 @@@
Item Exporters are used to export/serialize items into different formats.
"""
+from collections import Mapping
import csv
import io
- import pprint
import marshal
- import warnings
import pickle
+ import pprint
+ import warnings
from xml.sax.saxutils import XMLGenerator
- from scrapy.utils.serialize import ScrapyJSONEncoder
- from scrapy.utils.python import to_bytes, to_unicode, is_listlike
- from scrapy.item import BaseItem
+ from itemadapter import is_item, ItemAdapter
+
from scrapy.exceptions import ScrapyDeprecationWarning
+ from scrapy.item import _BaseItem
+ from scrapy.utils.python import is_listlike, to_bytes, to_unicode
+ from scrapy.utils.serialize import ScrapyJSONEncoder
__all__ = ['BaseItemExporter', 'PprintItemExporter', 'PickleItemExporter',
@@@ -57,21 -58,16 +59,24 @@@ class BaseItemExporter
"""Return the fields to export as an iterable of tuples
(name, serialized_value)
"""
+ item = ItemAdapter(item)
+
if include_empty is None:
include_empty = self.export_empty_fields
+
if self.fields_to_export is None:
- if include_empty and not isinstance(item, dict):
- field_iter = item.fields.keys()
+ if include_empty:
+ field_iter = item.field_names()
else:
field_iter = item.keys()
+ elif isinstance(self.fields_to_export, Mapping):
+ if include_empty:
+ field_iter = self.fields_to_export.items()
+ else:
+ field_iter = (
+ (x, y) for x, y in self.fields_to_export.items()
+ if x in item
+ )
else:
if include_empty:
field_iter = self.fields_to_export
@@@ -79,18 -75,9 +84,13 @@@
field_iter = (x for x in self.fields_to_export if x in item)
for field_name in field_iter:
- if field_name in item:
- field_meta = item.get_field_meta(field_name)
- value = self.serialize_field(field_meta, field_name, item[field_name])
+ if isinstance(field_name, str):
+ item_field, output_field = field_name, field_name
+ else:
+ item_field, output_field = field_name
+ if item_field in item:
- if isinstance(item, dict):
- field = {}
- else:
- field = item.fields[item_field]
- value = self.serialize_field(
- field, output_field, item[item_field]
- )
++ field_meta = item.get_field_meta(item_field)
++ value = self.serialize_field(field_meta, output_field, item[item_field])
else:
value = default_value
diff --cc tests/test_feedexport.py
index 691fa851c,f7013bc44..f5d1b0843
--- a/tests/test_feedexport.py
+++ b/tests/test_feedexport.py
@@@ -4,22 -4,22 +4,25 @@@ import o
import random
import shutil
import string
+import sys
import tempfile
import warnings
+from collections import OrderedDict
from io import BytesIO
+ from logging import getLogger
from pathlib import Path
from string import ascii_letters, digits
from unittest import mock
from urllib.parse import urljoin, urlparse, quote
from urllib.request import pathname2url
+import pytest
import lxml.etree
+ from testfixtures import LogCapture
from twisted.internet import defer
from twisted.trial import unittest
- from w3lib.url import path_to_file_uri
+ from w3lib.url import file_uri_to_path, path_to_file_uri
+ from zope.interface import implementer
from zope.interface.verify import verifyObject
import scrapy