Tengo una función que crea un json vacío y otra que sobreescribe el contenido de dicho json, pero de la manera en que lo tengo lo sobreescribe con un solo objeto cada vez a pesar de pasarle un listado de alrededor 10. ¿Cómo puedo sobreescribir TODA la información cada vez que llame a dicha función?
def override_json(folder_path, elements) -> None:
json_path = os.path.join(folder_path, 'data.json')
try:
with open(json_path, 'r') as json_file:
data = json.load(json_file)
except FileNotFoundError:
data = {}
for element in elements:
unique_key = str(datetime.now())
data[unique_key] = element.__dict__
with open(json_path, 'w') as json_file:
json.dump(data, json_file, indent=2)
Esta es la función desde donde lo llamo
def scrap_infinite_page() -> None:
clear_console()
current_datetime:[datetime] = datetime.now()
folder_path:[str] = create_folder(current_datetime)
options:[webdriver.ChromeOptions] = webdriver.ChromeOptions()
options.add_argument('--headless')
driver:[webdriver.WebDriver] = webdriver.Chrome(options=options)
index:[int] = 0
page_url = INFINITE_SCROLL_URL
driver.get(page_url)
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
try:
quotes:list[Quote] = []
quotes_elements = WebDriverWait(driver, MAX_TIME_DELAYED).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, "quote"))
)
for i in range(index, len(quotes_elements)):
quote_element = quotes_elements[i]
quote:Quote = extract_quote(quote_element)
quotes.append(quote)
index = len(quotes_elements)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
override_json(folder_path, quotes)
except Exception as e:
print("Error al obtener los elementos:", e)