IT개발/Python(파이썬)2010. 8. 27. 17:39
문서/파일 가져오기 - urllib객체 (http, ftp, file)

urllib 는 HTTP, FTP, local file 등에 관계없이 URL로 표현되는 모든 파일을 가져올 수 있다.


1) HTTP 프로토콜 상의 문서/파일 가져오기
import urllib

web = urllib.urlopen('http://www.python.org')

print web.headers                                     # 리턴된 헤더 출력
print web.read()                                        # 실제로 가져온 html 파일 출력

(실행 결과)
[citylock@nmsfile http]$ ./urllibHttp.py
Date: Fri, 27 Aug 2010 08:22:54 GMT
Server: Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9 OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2
Last-Modified: Thu, 26 Aug 2010 22:09:33 GMT
ETag: "105800d-46c3-48ec140c00140"
Accept-Ranges: bytes
Content-Length: 18115
Connection: close
Content-Type: text/html

(...   생략 : html 파일 .... )


2) FTP 파일 가져오기
import urllib

ftp = urllib.urlopen('ftp://people.linuxkorea.co.kr/pub/Python/KoreanCodes-1.4.tar.gz')
file = ftp.read()                                                                         # 원격서버로 부터 파일을 읽어온다.
f = open('KoreanCodes-1.4.tar.gz','wb')                                       # 파일을 저장하기위한 로컬디스크 파일 생성
f.write(file)                                                                             # 로컬디스크에 쓰기
f.close()


3) 로컬디스크 파일 가져오기
import urllib

text = urllib.urlopen('file://home/citylock/programing/python/threadi/threadingEvent.py')
print text



4)예외 처리 하기
import urllib

def getpage(url):
        try:
                f = urllib.urlopen(url)
                return f.read()
        except IOError, msg:
                print msg, url
                return None

text = getpage('http://dfdk.dsfkg.skjdk/')
(실행결과)
[citylock@nmsfile http]$ ./urllibError.py
[Errno socket error] (-2, 'Name or service not known') http://dfdk.dsfkg.skjdk/

** 참고 : 존재하지 않는 페이지 요청
=> 서버에 페이지가 존재하지 않는 경우 Exception 에러를 발생하지는 안는다. 본문의 내용을 보면 "Error 404: File Not Found" 을 볼수 가 있다.
( 생 략 ....)
<h1 class="title">Error 404: File Not Found</h1>

<p>The URL you requested was not found on this server.</p>
<p>Try our <a class="reference external" href="/">home page</a>, or our <a class="reference external" href="/search/">search engines</a> - or use one of
the other links on the left hand navigation.</p>
(생략 ....)


Posted by 시티락