2012-06-04 7 views
7

ディレクトリを開くプログラムを作ってから、正規表現を使ってパワーポイントの名前を取得し、ファイルをローカルに作成してその内容をコピーしようとしています。私はこれを実行すると動作するように見えますが、実際にファイルを開こうとするとバージョンが間違っていると言い続けます。Python urllibオンラインディレクトリの内容をダウンロードする

from urllib.request import urlopen 
import re 

urlpath = urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/') 
string = urlpath.read().decode('utf-8') 

pattern = re.compile('ch[0-9]*.ppt') #the pattern actually creates duplicates in the list 

filelist = pattern.findall(string) 
print(filelist) 

for filename in filelist: 
    remotefile = urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/' + filename) 
    localfile = open(filename,'wb') 
    localfile.write(remotefile.read()) 
    localfile.close() 
    remotefile.close() 
+2

** RegExでHTMLを解析しないでください。http://stackoverflow.com/a/1732454/851737を参照してください。 lxmlやBeautifulSoupのようなHTML解析ライブラリを使用してください。 – schlamar

+0

美しいです。あなたのお勧めをありがとう。 – davelupt

答えて

8

このコードは私のために働いた。あなたのファイルがそれぞれのpptファイルを複製していたので少し修正しました。

from urllib2 import urlopen 
import re 

urlpath =urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/') 
string = urlpath.read().decode('utf-8') 

pattern = re.compile('ch[0-9]*.ppt"') #the pattern actually creates duplicates in the list 

filelist = pattern.findall(string) 
print(filelist) 

for filename in filelist: 
    filename=filename[:-1] 
    remotefile = urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/' + filename) 
    localfile = open(filename,'wb') 
    localfile.write(remotefile.read()) 
    localfile.close() 
    remotefile.close() 
+0

ありがとう、あなたはチャンピオンです。 – davelupt

+0

downvoteの理由のために私のコメントを見る(上記のhttp://stackoverflow.com/questions/10875215/python-urllib-downloading-contents-of-an-online-directory#comment14174956_10875215) – schlamar

+0

これは素晴らしいです、ありがとう – Anuj

関連する問題