Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在json文件中插入数据_Python_Json_File - Fatal编程技术网

Python 在json文件中插入数据

Python 在json文件中插入数据,python,json,file,Python,Json,File,代码在json文件中插入了错误的结构 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

代码在json文件中插入了错误的结构

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()

我看到了一系列问题,大多数问题要么在循环内部,要么在循环外部,要么在循环内部

  • 在a.find_all(“div”,{'class':'g'):中为子变量设置循环内的变量
    h2
    div
    ,但将它们添加到循环外的
    数据中,因此只会添加最后的值
  • 此外,您为循环内的每个键初始化数据,应该在循环外完成,否则每次都会重新初始化
  • 每次打开要附加到它的文件时,我只做一次
  • 并且,在每个循环中初始化驱动程序
  • 请求
    selenium.webdriver.chrome.options.options
    都是未使用的导入
因此,我将其更改为:

urls = {}
urls['Av'] = {'Áa', 'Bb'}

data = {}
driver = webdriver.Chrome()
with open("data_file.json", "a") as write_file: 
    for key, value in urls.items():
        data[key] = []. # initialize only once per key

        for x in value: 
            url = 'https://www.google.pt/search?q=' + key + '%20' + x
            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].append({'h2': h2, 'div': div})  # update data for every h2/div found

    json.dump(data, write_file, indent=4) # This write can be done once, outside all loops!

driver.quit()

对我来说测试有点困难,但希望能有所帮助!快乐编码

定义“错误结构”,然后继续定义“良好结构”。然后给我们一个你想存储的数据示例,以及它当前存储的数据。如果您有任何错误,请在代码块中发布完整的堆栈跟踪。它输出以下内容:{“Av”:[{“h2”:null,“div”:null}]}{“Av”:[{“h2”:null,“div”:null}]}请将其作为编辑内容包含在代码块的帖子中,而不是作为注释,使用open(“data\u file.json”,“a”)
时要非常小心。这意味着每次写入新版本的
数据时,您都会追加到文件中。这将导致一个技术上无效的
.json
文件。你的意思是在
for
循环结束后进行此操作吗?@Alvaro你仍然没有更新你的问题而不是评论部分。投票结束此问题,直到添加更多详细信息。我认为首先您应该
加载
JSON文件,然后
使用获取的数据更新
,然后最后使用
转储
将其写入文件。