将 URL 请求的内容写入文件 [英] Write contents of URL request to file

查看:28
本文介绍了将 URL 请求的内容写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入 urllib.requestpage = urllib.request.urlopen('http://crypto-bot.hopto.org/server/list.php')f = open("test.txt", "w")f.write(str(page))f.close()打印(page.read())

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

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

文件输出:

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

解决方案

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

在控制台中:

<预><代码>>>>导入 urllib>>>urllib.urlretrieve('http://crypto-bot.hopto.org/server/list.php','test.txt')('test.txt', )

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

ALF管理中心非国大ARG...等等...

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

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?

解决方案

Use urllib.urlretrieve (urllib.request.urlretrieve in 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

ALF
AMC
ANC
ARG
...etc...

这篇关于将 URL 请求的内容写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆