php에는 아래와 같은 snoopy 라는 강력한 라이브러리가 있다.
[강좌] php용 강력하면서 쉬운 소켓(socket)클래스 , Snoopy

 

파이썬에는 없는 것일까? 찾아 보자.

1. BeautifulSoup 이라는 라이브러리가 있음.

2. 1.의 라이브러리는 느리다는 평이 있다.  아래는 직접 작업하기

[파이썬마을]특정 웹페이지의 링크의 일부 가져오기 (기본적인 답변)

[파이썬마을]urllib 모듈로 그림까지 가져오려면?? (쓸만한 답변코드 있음)

#! /usr/local/bin/python
# ex:ts=4
import urllib, urlparse
import re, os.path, os
urlfind1 = re.compile(r'[<](\w*)[^>]*[Ss][Rr][Cc]=([^"\' ]\S*)[^>]*[>]')
urlfind2 = re.compile(r'[<](\w*)[^>]*[Ss][Rr][Cc]=["\']([^"\']*)["\'][^>]*[>]')
def recurget(url, got=None, depth=0):
    if got is None: got = []
    print "   "*depth + "Getting %s ..." % url
    content = urllib.urlopen(url).read()
    urls = urlfind1.findall(content) + urlfind2.findall(content)
    filepath = urlparse.urlparse(url)[2][1:]
    try:
        os.makedirs(os.path.dirname(filepath))
    except OSError:
        pass
    open(filepath, "w").write(content)
    for tag, target in urls:
        turl = urlparse.urljoin(url, target)
        print "   "*depth + " + Tag found (%s to %s) => %s" % (tag, target, turl)
        if turl not in got:
            got.append(turl)
            recurget(turl, got, depth+1)
if __name__ == "__main__":
    import sys
    for url in sys.argv[1:]:
        recurget(url)

 

Python File Read Write with Urllib2

+ Recent posts