用于在我的服务器上下载XML文件的Python脚本

0 投票
2 回答
2936 浏览
提问于 2025-04-15 22:03

我需要一个Python脚本,完成以下几个步骤:

  1. 连接到一个网址,这个网址会返回一个数字,比如1200。

  2. 用这个数字去下载一些XML文件,文件名从1到这个数字,比如1到1200。

  3. 把这些文件存放在一个特定的文件夹里。

抱歉,我从来没有写过Python脚本,如果你能指导我一下就太好了(最好能加一些注释)。

我会把这个脚本作为定时任务运行,如果这有影响的话。

2 个回答

1

如果你从来没有写过Python脚本,建议你先找一个Python教程学习一下。

当你对Python有了初步了解后,可以去看看

http://docs.python.org/library/

关于第一个问题,你可以查看

http://docs.python.org/library/internet.html

对于第二个问题,你可以尝试这样的做法

max = 10 # assume from #1
for x in range(1, max+1):
    filename = 'some_file-' + str(x) + '.xml'
    # download the file - see above url for internet protocols
    # see http://docs.python.org/library/stdtypes.html#file-objects
    # for help on files

这个问题描述得很模糊,虽然看起来不像是作业,但如果你完全不懂这种语言,尤其是在cron中运行时,做这个可能不是个好主意。

2

下面是一个使用 urllib 的例子:

import urllib
import os

URL = 'http://someurl.com/foo/bar'
DIRECTORY = '/some/local/folder'

# connect to a URL, and that URL will return a number like 1200.
number = int(urllib.urlopen(URL).read())

# Use the number, to download xml files named: 
# 1 to x where x is the number from #1.
# store the files in a particular directory.
for n in xrange(1, number + 1):
    filename = '%d.xml' % (n,)
    destination = os.path.join(DIRECTORY, filename)
    urllib2.urlretrieve(URL + '/' + filename, destination)

撰写回答