From 33e257a66e3f1e549ca671f8b85afa8855e4cb15 Mon Sep 17 00:00:00 2001 From: Mohammad Hijjawi Date: Thu, 5 Nov 2026 18:50:41 +0000 Subject: [PATCH] fix(utils): write every row's keys in export_to_csv export_to_csv took the CSV header from the first row only, so a later row with a key the first row lacks made csv.DictWriter raise "ValueError: dict contains fields not in fieldnames" and the file was left with only the rows written before it. Scraped results often have optional fields that only some items carry. Build the header from the keys of all rows in order of first appearance; missing values are written as empty cells. --- scrapegraphai/utils/data_export.py | 4 ++- tests/utils/data_export_test.py | 43 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/utils/data_export_test.py diff --git a/scrapegraphai/utils/data_export.py b/scrapegraphai/utils/data_export.py index 498f661b0..73369e820 100644 --- a/scrapegraphai/utils/data_export.py +++ b/scrapegraphai/utils/data_export.py @@ -36,7 +36,9 @@ def export_to_csv(data: List[Dict[str, Any]], filename: str) -> None: logger.warning("No data to export") return - keys = data[0].keys() + # Collect the keys of every row, in order of first appearance, so rows + # with extra or missing keys do not make DictWriter raise. + keys = list(dict.fromkeys(key for row in data for key in row)) with open(filename, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=keys) writer.writeheader() diff --git a/tests/utils/data_export_test.py b/tests/utils/data_export_test.py new file mode 100644 index 000000000..5d97a0df2 --- /dev/null +++ b/tests/utils/data_export_test.py @@ -0,0 +1,43 @@ +import csv + +from scrapegraphai.utils.data_export import export_to_csv + + +def read_csv(path): + with open(path, newline="", encoding="utf-8") as f: + reader = csv.DictReader(f) + return reader.fieldnames, list(reader) + + +def test_export_to_csv_writes_rows(tmp_path): + path = tmp_path / "out.csv" + export_to_csv([{"name": "a", "price": 1}, {"name": "b", "price": 2}], str(path)) + + fieldnames, rows = read_csv(path) + assert fieldnames == ["name", "price"] + assert rows == [{"name": "a", "price": "1"}, {"name": "b", "price": "2"}] + + +def test_export_to_csv_rows_with_different_keys(tmp_path): + path = tmp_path / "out.csv" + data = [ + {"name": "a", "price": 1}, + {"name": "b", "price": 2, "rating": 4.5}, + {"name": "c"}, + ] + + export_to_csv(data, str(path)) + + fieldnames, rows = read_csv(path) + assert fieldnames == ["name", "price", "rating"] + assert rows == [ + {"name": "a", "price": "1", "rating": ""}, + {"name": "b", "price": "2", "rating": "4.5"}, + {"name": "c", "price": "", "rating": ""}, + ] + + +def test_export_to_csv_empty_data_writes_nothing(tmp_path): + path = tmp_path / "out.csv" + export_to_csv([], str(path)) + assert not path.exists()