【问题标题】:Write contents of URL request to file将 URL 请求的内容写入文件
【发布时间】:2013-10-10 02:20:21
【问题描述】:

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

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

【问题讨论】:

    标签: python urllib


    【解决方案1】:

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

    在控制台中:

    >>> 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...
    

    【讨论】:

      【解决方案2】:

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

      这样做:

      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)
      

      【讨论】:

      • TypeError: write() argument must be str, not bytes
      • 哪个版本的 Python?
      • 我正在使用Python 3.5.1
      • 将字节流转换成这样的字符串 content = str(page.read())
      【解决方案3】:

      当您写入文件时,您并没有从urlopen 文件中读取内容。

      另外,shutil.copyfileobj()

      【讨论】:

        猜你喜欢
        • 2021-08-15
        • 1970-01-01
        • 2013-08-01
        • 2010-11-09
        • 1970-01-01
        • 2016-09-28
        • 2012-05-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多