Python 将 URL 请求的内容写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19285966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:20:47  来源:igfitidea点击:

Write contents of URL request to file

pythonurllib

提问by pclever1

I am trying to fetch a list from a php file using python and save it to a file:

我正在尝试使用 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())

Output on screen (divided onto four lines for readability):

屏幕上的输出(分为四行以提高可读性):

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

Output in file:

文件中的输出:

<http.client.HTTPResponse object at 0x00000000031DAEF0>

Can you tell me what I am doing wrong?

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

回答by Ignacio Vazquez-Abrams

You're not reading the content from the urlopenfile-like when you write to the file.

urlopen当您写入文件时,您不是从文件中读取内容。

Also, shutil.copyfileobj().

还有,shutil.copyfileobj()

回答by tehsockz

Use urllib.urlretrieve(urllib.request.urlretrievein Python 3).

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

In the console:

在控制台中:

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

This results in a file, test.txt, being saving in the current working directory with the contents

这会生成一个文件,test.txt,其内容保存在当前工作目录中

ALF
AMC
ANC
ARG
...etc...

回答by Spaceghost

You need to read from the file object before writing to the file. Also you should the same object to both file and screen.

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

Do this:

做这个:

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)