在for循环中,Json文件没有从python字符串数组正确导出

2024-04-26 03:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个网站刮刀,刮刀的网站,并寻找特定的关键字在一个网站,如果它找到关键字,它会调用该网站的生产或非生产,然后它会导出到一个json文件,这样我可以得到它与c#以后,但问题是,json导出方法是不导出没错,我对pyhton和json都是新手。你知道吗

我已经尝试了所有的方法和每种语法,但似乎没有什么工作,因为我希望它是。你知道吗

这是我的python代码

from bs4 import BeautifulSoup
import requests
import json
import os
import pandas as pd
import numpy as np

# this scraps the websites that i give it
def scrap_website():

    pages = ['https://www.youtube.com/watch?v=tHI2NIaNrGk',
            'https://aljazeera.com', 'https://www.svt.se']

    for site in pages:
        page = requests.get(site)
        soup = BeautifulSoup(page.content, 'html.parser')

        if 'Game' in soup.getText():
            is_productive = False
            json_map = {}
            json_map["websiteLink"] = site
            json_map["isProductive"] = is_productive
            json_text = json.dumps(json_map)

        else:
            is_productive = True

            json_map = {}
            json_map["websiteLink"] = site
            json_map["isProductive"] = is_productive
            json_text = json.dumps(json_map)

        data = []
        data.append(json_text)
        with open('data\\data.json', 'a') as json_file:
             json.dump(data, json_file, indent=2, separators=(
                 ", ", "  "), sort_keys=True)


scrap_website()

这是我得到的json代码

[
  "{\"websiteLink\": \"https://www.youtube.com/watch?v=tHI2NIaNrGk\", \"isProductive\": false}"
][
  "{\"websiteLink\": \"https://aljazeera.com\", \"isProductive\": true}"
][
  "{\"websiteLink\": \"https://www.svt.se\", \"isProductive\": true}"
]

Tags: texthttpsimportcomjsonmapdatais
1条回答
网友
1楼 · 发布于 2024-04-26 03:20:46

您可以在同一个json中添加所有节点,声明一个数组,然后转到将每个网站添加为数组的节点,以便:

在than循环之前声明数组

json_map = []

对于每个网站

site_node = {}

site_node["websiteLink"] = site

site_node["isProductive"] = is_productive

json_map.append(site_node)

最后将json保存在循环外部

with open('data.json', 'w') as outFile:

    json.dump(json_map, outFile)

在加载json数组并使用一个简单的for

相关问题 更多 >