2010-12-21 81 views
0
import re 
import string 
import shutil 
import os 
import os.path 
import time 
import datetime 
import math 
import urllib 
from array import array 
import random 

filehandle = urllib.urlopen('http://www.google.com/') #open webpage 
s = filehandle.read() #read 
print s #display 

#what i plan to do with it once i get the first part working 
#results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s) 
#earnings = '$ ' 
#for money in results: 
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6] 
#print earnings 
#raw_input() 

這是我迄今爲止的代碼。現在我已經看過所有其他論壇給出的解決方案,如腳本的名稱,這是parse_Money.py,並且我已經嘗試使用urllib.request.urlopen來做,而且我已經嘗試在python 2.5,2.6上運行它,和2.7。如果有人有任何建議,將非常歡迎,謝謝大家! --Matt關於urllib AttributeError:'模塊'對象沒有屬性'urlopen'

--- 編輯 --- 我也試過這個代碼和它的工作,所以即時通訊思想的某種語法錯誤的,所以如果有人用鋒利的眼睛可以指出來,我會非常感激。

import shutil 
import os 
import os.path 
import time 
import datetime 
import math 
import urllib 
from array import array 
import random 
b = 3 

#find URL 
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :') 



while b == 3: 
    #get file name 
    file1 = raw_input('Enter a file name for the downloaded code:') 
    filepath = file1 + '.txt' 
    if os.path.isfile(filepath): 
     print 'File already exists' 
     b = 3 
    else: 
     print 'Filename accepted' 
     b = 4 

file_path = filepath 
#open file 
FileWrite = open(file_path, 'a') 


#acces URL 
filehandle = urllib.urlopen(URL) 

#display souce code 
for lines in filehandle.readlines(): 
    FileWrite.write(lines) 
    print lines 
print 'The above has been saved in both a text and html file' 

#close files 
filehandle.close() 
FileWrite.close() 
+1

看起來你完全* *搞砸了你的Python安裝執行這個腳本。什麼是操作系統以及文件名爲'urllib .__ file__'的內容是什麼? – AndiDog 2010-12-21 07:17:01

+0

我試過在IDLE上運行你的錯誤代碼,它執行的很好。雖然我除了'urllib'外沒有任何東西。可能你可能想嘗試這樣做。除此之外,我不認爲在第一個例子中你的代碼有什麼問題。 – anirvan 2010-12-21 08:45:15

回答

1

it appearsurlopen方法是urllib.request模塊中使用和你期待不是在urllib模塊。

經驗法則 - 如果您得到AttributeError,該字段/操作不存在於特定模塊中。

編輯 - 感謝AndiDog指出 - 這是一個適用於Py 3.x的解決方案,不適用於Py2.x!

+0

的事情是如果我導入urllib.request或如果我打電話urllib.request.urlopen它說同樣的事情。真正令我感到困惑的是,我今天早些時候運行的這些命令在 – Matt 2010-12-21 07:21:12

+1

以上看到了這些命令。他說他使用的是Python 2.x,而不是3.x!他們在Python 3.0和更新的版本中將'urlopen'移動到'urllib.request'中。 – AndiDog 2010-12-21 07:21:52

+0

我的壞!編輯迴應以表明AndiDog的觀察結果。除了他檢查文件位置的建議之外,還可以調用'urllib .__ dict __。get(「urlopen」)'來檢查模塊是否實際上包含該操作。 – anirvan 2010-12-21 07:37:06

0

urlopen函數實際上是在urllib2模塊中。嘗試導入urllib2並使用urllib2.urlopen

+2

它在兩個。 http://docs.python.org/library/urllib.html#urllib.urlopen – AndiDog 2010-12-21 07:54:37

0

我看到您正在使用Python2或至少打算使用Python2。 urlopen helper函數在Python2的urllib和urllib2中均可用。

你需要做的這個是什麼,對正確版本的巨蟒

C:\Python26\python.exe yourscript.py 
相關問題