我试图打印网址文件中的行,但是我收到的错误是:
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 :(得分: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
具有误导性:迭代字符串会产生字符,而不是行。