【问题标题】:result value store in array or json结果值存储在数组或 json 中
【发布时间】:2020-01-18 02:57:24
【问题描述】:

我尝试解决了很久。

我想将 result 值存储在数组或 JSON 中作为一组数据。

请帮助检查下面的代码。我还是不明白。

我想要的结果:

result = ["Price Milk 80","Price Pen 30","Price Tomato 40","Price Banana 40"]

for 循环中使用并将所有数据作为一组发送。

我当前的结果如下,打印到控制台:

['Price Milk 80']
['Price Pen 30']
['Price Tomato 40']
['Price Banana 40']
import requests
import json
import locale
import csv

file = csv.reader(open('file.csv'), delimiter=',')
for line in file:
    hd = line[0]
    url = line[1]
    name = line[2]
    headers = {
        'Referer': hd
    }
    request = requests.get(url, headers=headers).json()
    con_str = str(request["item"]["price"])
    total_price = con_str[:-5]
    msg = (name + " " + total_price)
    result = [(msg)]
    print(result)

【问题讨论】:

  • 如果您不熟悉 Python 的基础知识,我强烈建议您从那里开始。 Stack Overflow 并不意味着取代指南或教程。
  • @AMC 请您帮忙查看代码。
  • 你至少猜到你的代码在哪里没有做你想做的事吗?
  • @GRquanti 输出:['Price Milk 80']
    ['Price Pen 30']
    ['Price Tomato']
    ['Price Banana 40'] 如何将它们保存到列表中,这样我的输出将类似于:["Price Milk 80","Price Pen 30","Price Tomato 40","Price Banana 40"]
  • @TanaphonPrayoonprasop 这看起来像 HTML。同样,我建议您查看一些指南/教程,包括关于网络抓取的指南/教程。

标签: python python-3.x python-requests


【解决方案1】:

尝试在循环之前定义一个result 列表,然后在循环内为每个msg 附加一个新的result 元素,最后在循环之后打印result 列表:

result = []
for line in file:
   ...
   result.append(msg)

print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多