无法使用“urllib2”打印文件中的内容

时间:2015-02-12 02:09:30

标签: python

我试图打印网址文件中的行,但是我收到的错误是:

    with html as ins:
    AttributeError: __exit__

下面发布的是我的代码

  import urllib2

  response = urllib2.urlopen('------------------')

  html = response.read()
  counter = 0;
  with html as ins:
  array = []
  for line in ins:
     counter = counter+1
     print "cluster number is:", counter  
     print line  

1 个答案:

答案 0 :(得分:1)

如果要按原样从URL中写入字节(无解码/编码):

#!/usr/bin/env python2
import urllib2
import shutil
import sys
from contextlib import closing

with closing(urllib2.urlopen(url)) as response:
    shutil.copyfileobj(response, sys.stdout)

它期望response使用的字符编码与您的终端使用的字符编码相同,否则您将看到mojibake。请参阅A good way to get the charset/encoding of an HTTP response in Python


问题中的代码包含多个错误,例如:

  • 错误的缩进
  • 它尝试使用str对象作为上下文管理器,导致AttributeError__exit__方法未定义),因为str对象未实现{{3 }}
  • for line in ins具有误导性:迭代字符串会产生字符,而不是行。