【问题标题】:Json file not exporting correctly from python string array in a for loopJson 文件未在 for 循环中从 python 字符串数组正确导出
【发布时间】:2019-11-21 03:15:56
【问题描述】:

我正在制作一个网站抓取工具,用于抓取网站并在网站中查找特定关键字,如果找到关键字,它将调用该网站为生产性网站或非生产性网站,然后将该信息导出到一个 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}"
]

【问题讨论】:

  • 追加到数组,而不是字符串,然后序列化所有数据
  • 也将with语句从循环中移出,并在循环外创建list

标签: python json web-scraping beautifulsoup export


【解决方案1】:

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

在循环之前声明数组

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循环它

【讨论】:

  • 谢谢,但现在它什么也没写,它给了我这个错误 AttributeError: 'dict' object has no attribute 'add'
  • 使用追加而不是添加
  • 对不起,但仍然无法正常工作,它给出了同样的错误,但如果你愿意,它是'dict'对象没有属性'append',你可以在github.com/abodsakah/unproductive-scraper检查整个事情
  • @abodsakka 你将 json_map 从列表重新定义为 if 块内的映射
猜你喜欢
  • 2017-07-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2015-09-22
  • 2020-07-15
相关资源
最近更新 更多