【问题标题】:writing Json file from python script [duplicate]从python脚本编写Json文件[重复]
【发布时间】:2016-08-11 13:59:49
【问题描述】:

作为初学者,我们正忙于使用 python 中的抓取工具。它几乎完成了,但现在我们想要一个 JSON 文件中的结果。我们试过了,但它不起作用。有没有代码英雄可以帮助我们?

from bs4 import BeautifulSoup
import urllib

jaren = [str("2010"), str("2012")]
DESIRED_COLUMNS = {1, 2, 5}  # it is a set

for Jaargetal in jaren:
    r = urllib.urlopen("http://www.nlverkiezingen.com/TK" + Jaargetal +".html").read()
    soup = BeautifulSoup(r, "html.parser")
    tables = soup.find_all("table")

for table in tables:
    header = soup.find_all("h1")[0].getText()
    print header

    trs = table.find_all("tr")[0].getText()
    print '\n'
    for tr in table.find_all("tr")[:22]: 
          print "|".join([x.get_text().replace('\n', '') 
      for index, x in enumerate(tr.find_all('td')) 
      if index in DESIRED_COLUMNS])

【问题讨论】:

  • 这是您的实际代码吗?因为你现在有语法和缩进问题。
  • @idjaw 我已经更新了代码。现在没有错误了。
  • 您仍然有缩进问题。特别是r = urllib.urlopen("http://www.nlverkiezingen.com/TK" + Jaargetal +".html").read()。那个for循环应该是什么? for Jaargetal in jaren 下面的所有内容都应该在那个循环内吗?你应该确保你的代码是你正在运行的代码的精确表示
  • 对不起,现在代码应该可以工作了。里面有一些尝试的东西。
  • 请仔细看代码。它仍然没有正确缩进。看看for Jaargetal in jaren:。代码没有在该行下方缩进。

标签: python json


【解决方案1】:

您可以像这样将 JSON 写入文件:

import json
d = {"foo": "bar"}
with open("output.json", "w") as f:
    json.dump(d, f)

【讨论】:

    【解决方案2】:

    json.dumps() 是函数。它将字典转换为 str 对象。 Docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2023-04-03
      • 2016-12-07
      • 2013-04-22
      • 2013-12-25
      • 2013-02-07
      • 1970-01-01
      相关资源
      最近更新 更多