Python3从txt文件中的URL下载csv文件

时间:2020-03-20 18:57:38

标签: python json csv urllib

下面的代码将从URL中解析JSON,以检索10个URL,并将它们放入output.txt文件中。

import json
import urllib.request

response = urllib.request.urlopen('https://json-test.com/test').read()
jsonResponse = json.loads(response)
jsonResponse = json.loads(response.decode('utf-8'))
for child in jsonResponse['results']:
    print (child['content'], file=open("C:\\Users\\test\\Desktop\\test\\output.txt", "a"))

现在output.txt中有10个指向csv文件的链接,试图弄清楚如何下载和保存10个文件。试图做这样的事情,但不起作用。

urllib.request.urlretrieve(['content'], "C:\\Users\\test\\Desktop\\test\\test1.csv")  

即使我能进行上述工作,它也仅适用于1个文件,output.txt中也有10个文件链接。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Here is a exhausting guide on how to download files over http

如果文本文件每行包含一个链接,则可以遍历以下行:

file = open('path/to/file.ext', 'r')
id = 0
for line in file:
   # ... some regex checking if the text is actually a valid url
   response = urllib.request.urlretrieve(line, 'path/to/file' + str(id) + '.ext')
   id+=1