2015-02-12 52 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