2015-02-12 46 views
0

我想打印存在于但是URL文件中的行打印的文件中的内容,我得到一个错误,指出:无法使用“的urllib2”

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 
+0

请修复您的缩进。 – Marcin 2015-02-12 02:10:50

+0

是的..!我修正了缩进但问题仍然存在 – user3787061 2015-02-12 02:11:32

+0

这两行仍然有错误的缩进:'用html作为ins:array = []'。请仔细检查。也许这是问题所在。 – Marcin 2015-02-12 02:14:50

回答

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) 

它希望是t他使用的字符编码response是您的终端使用相同的字符编码,否则您会看到mojibake。见A good way to get the charset/encoding of an HTTP response in Python


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

  • 错误压痕
  • 它试图使用str对象作为导致AttributeError(没有定义__exit__法)上下文管理因为str对象不实现the context manager protocol
  • for line in ins误导:迭代字符串会产生字符,而不是行。
+0

@Sebastian我正在寻找提取值并将它们复制到一个数组中并逐行打印 – user3787061 2015-02-12 02:27:41

+0

@ user3787061:将您的问题分解为一系列可轻松理解的较小任务,例如1.您想要什么一行一行打印? (它是url的内容吗?它是什么?它是一个带有json文本或html文档或xml文档的字节流?)2.它是什么意思*“提取值”* - 提供一个示例输入为一个字符串和相应的输出数组。更新你的问题。不要在评论中提供更多信息。 – jfs 2015-02-12 02:36:18