diff --git a/scrapegraphai/utils/data_export.py b/scrapegraphai/utils/data_export.py index 498f661b..73369e82 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 00000000..5d97a0df --- /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()