如何从服务器下载.log文件并使用Python将其保存到本地磁盘

时间:2018-03-01 12:41:06

标签: python python-3.x urllib

我正在尝试从服务器下载错误日志文件,例如IIS日志,HTTP API错误日志,并将其保存到我的磁盘。这些日志包含.log扩展名。

尝试下面的代码下载,它适用于文本文件,但它不适用于.log类型的文件:

from urllib.request import urlopen
response = urlopen('https://servername/path/errorlog.txt') #doesn't work for response = urlopen('https://servername/path/errorlog.log')
data = response.read()

# Write data to file
filename = "test.txt"
file_ = open(filename, 'w')
file_.write(data)
file_.close()

This is one error log file

这是我收到的错误消息:

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    response = urlopen(url)
  File "C:\Python\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Python\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Python\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Python\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

你有解决这个问题的方法吗?

0 个答案:

没有答案