The code inserts wrong structure json into file
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json
urls = {}
urls['Av'] = {'Áa', 'Bb'}
data = {}
for key, value in urls.items():
for x in value:
url = 'https://www.google.pt/search?q=' + key + '%20' + x
driver = webdriver.Chrome()
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
a = soup.find("body")
for child in a.find_all("div", {'class': 'g'}):
h2 = child.find("span", {'class': 'Q8LRLc'})
div = child.find("a", {'class': 'Fx4vi'})
data[key] = []
data[key].append({'h2': h2, 'div': div})
print(data)
with open("data_file.json", "a") as write_file:
json.dump(data, write_file, indent=4)
driver.quit()
with open("data_file.json", "a"). This means that you are appending to the file, each time writing a new version ofdata. This will result in a technically invalid.jsonfile. Did you mean to have this after the end of theforloop?