【问题标题】:Python loop through table of URL's and get data from those websitesPython 循环遍历 URL 表并从这些网站获取数据
【发布时间】:2022-06-13 14:03:31
【问题描述】:

我正在尝试遍历一个表,该表包含我想要从中获取 JSON 数据的所有网站。

def getResponse(url):
    operUrl = urllib.request.urlopen(url)
    if(operUrl.getcode()==200):
        data = operUrl.read()
        jsonData = json.loads(data)
    else:
        print("Error receiving data", operUrl.getcode())
    return jsonData

def main():

    urlData = ("site1.com")
#Needs to loop all the URL's inside
#urlData = ["site1.com", "site2.com"] and so on

    jsonData = getResponse(urlData)

    for i in jsonData["descriptions"]:
        description = f'{i["groups"][0]["variables"][0]["content"]}'

data = data = {'mushrooms':[{'description': description,}]}

    with open('data.json', 'w') as f:
        json.dump(data, f, ensure_ascii=False)
    print(json.dumps(data, indent=4, ensure_ascii=False), )

运行后将其保存到 data.json 文件中,如下所示

{
    "mushrooms": [
        {
            "description": "example how it looks",
            
        }
    ]
}

它确实从一个站点获取数据,但我希望它遍历表中的多个 URL,例如

编辑: 我通过像这样循环让它工作

for url in urlData:

我将所有网站链接都放在一个表 urlData 中,然后将从这些网站找到的数据附加到另一个表中。

【问题讨论】:

  • 你能发布一个你有json响应的例子吗?
  • 当它获取数据时,它会将其转换为 JSON 格式 data = {'mushrooms':[{'description': description,}]},然后将其粘贴到文件中 with open('data.json', 'w') as f: json.dump(data, f, ensure_ascii=False) print(json.dumps(data, indent=4, ensure_ascii=False), ) 抱歉,我忘记将其包含在上面的代码中
  • 更新问题以便更好地理解 :) 如果您发布 jsonData["descriptions"] 的部分确切内容,我们可以提供帮助
  • for urlData in ["site1.com", "site2.com"]: jsonData = 等等等等
  • 标准规则:如果您使用for-loop,那么您必须使用list 来保留所有结果。

标签: python json


【解决方案1】:

我通过这样的循环让它工作

for url in urlData:

我将所有网站链接都放在一个表 urlData 中,然后将从这些网站找到的数据附加到另一个表中。完成后,它会将数据转储到 json 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多