파이썬에서 url을 입력해서 download 받는 방법이다.
www.python.org에서 html을 다운로드 해보자
import urllib
# Get a file-like object for the Python Web site's home page.
f = urllib.urlopen("http://www.python.org")
# Read from the object, storing the page's contents in 's'.
s = f.read()
f.close()
urllib를 import하고 urllib.urlopen() 함수를 호출하여 읽어들일 url을 나타내는 네트워크 객체를 생성하고 s라는 변수에 읽어 들인다.
그러면 끝 !
print s 라고 치면 읽어들인 것을 프린트 한다.
urlopen()함수에 대해서 알고 싶으면 참고 : http://docs.python.org/library/urllib.html#urllib.urlopen
다음은 Post 메서드로 접근하는 방법이다.
# Search the Vaults of Parnassus for "XMLForms".
# First, encode the data.
data = urllib.urlencode({"find" : "XMLForms", "findtype" : "t"})
# Now get that file-like object again, remembering to mention the data.
f = urllib.urlopen("http://www.vex.net/parnassus/apyllo.py", data)
# Read the results back.
s = f.read()
s.close()
위의 data를 print해보면 별거 아니다. 결국 파라메터를 만들어 주고, 유니코드 문자 등에 대해서 urlencoding을 해주는 것 뿐이다.
>>> data = urllib.urlencode({"find" : "XMLForms", "findtype" : "t"})
>>> data
'findtype=t&find=XMLForms'
>>> data = urllib.urlencode({"find" : "XMLForms", "findtype" : "여긴지구"})
>>> data
'findtype=%EC%97%AC%EA%B8%B4%EC%A7%80%EA%B5%AC&find=XMLForms'
이번에는 Get 메서드로 접근하는 방법이다. data에 알맞은 파라메터를 넣으면 되겠다.
# We have the encoded data. Now get the file-like object...
f = urllib.urlopen("http://www.vex.net/parnassus/apyllo.py?" + data)
# And the rest...
참 쉽다.
'Programing > Python' 카테고리의 다른 글
Python subprocess Popen에서 좀비프로세스 방지 (zombie-processes 방지) (0) | 2011.10.14 |
---|---|
Python CSV 파일을 xls 파일로 변환하기 / convering csv2xls using Python (csv to xls) (1) | 2010.10.11 |