4

我正在尝试使用 python 从 php 文件中获取列表并将其保存到文件中:

import urllib.request

page = urllib.request.urlopen('http://crypto-bot.hopto.org/server/list.php')

f = open("test.txt", "w")
f.write(str(page))
f.close()

print(page.read())

屏幕输出(为了便于阅读,分为四行):

ALF\nAMC\nANC\nARG\nBQC\nBTB\nBTE\nBTG\nBUK\nCAP\nCGB\nCLR\nCMC\nCRC\nCSC\nDGC\n
DMD\nELC\nEMD\nFRC\nFRK\nFST\nFTC\nGDC\nGLC\nGLD\nGLX\nHBN\nIXC\nKGC\nLBW\nLKY\n
LTC\nMEC\nMNC\nNBL\nNEC\nNMC\nNRB\nNVC\nPHS\nPPC\nPXC\nPYC\nQRK\nSBC\nSPT\nSRC\n
STR\nTRC\nWDC\nXPM\nYAC\nYBC\nZET\n

文件中的输出:

<http.client.HTTPResponse object at 0x00000000031DAEF0>

你能告诉我我做错了什么吗?

4

3 回答 3

15

使用urllib.urlretrieveurllib.request.urlretrieve在 Python 3 中)。

在控制台中:

>>> import urllib
>>> urllib.urlretrieve('http://crypto-bot.hopto.org/server/list.php','test.txt') 
('test.txt', <httplib.HTTPMessage instance at 0x101338050>)

这导致文件 ,test.txt与内容一起保存在当前工作目录中

ALF
AMC
ANC
ARG
...etc...
于 2013-10-10T02:24:00.573 回答
3

在写入文件之前,您需要从文件对象中读取。此外,您应该对文件和屏幕使用相同的对象。

做这个:

import urllib.request

page = urllib.request.urlopen('http://crypto-bot.hopto.org/server/list.php')

f = open("test.txt", "w")
content = page.read()
f.write(content)
f.close()

print(content)
于 2013-10-10T02:26:32.853 回答
0

urlopen当您写入文件时,您不会像从文件中读取内容一样。

另外,shutil.copyfileobj().

于 2013-10-10T02:23:31.133 回答