전공 과목 이수1👨‍💻/파이썬

크롤링 공부 - urllib, urlopen

천숭이 2021. 12. 2. 20:36

사이트 링크/robots.txt 를 통해 웹페이지의 조건 확인

** Request 요청 주의 할 점 - 서버 부하 고려 (간격을 충분히 두고 작업하기)

 

- http통신은 한번 연결하고 통신하면 연결이 끊긴다. 일회성

 

# urllib

import urllib.request as req  # 요청 라이브러리

img_url = 'https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMTExMTRfMTQw%2FMDAxNjM2ODg0NTE4MzIw.8f54g2487ow0ZT69rDSjwTWUMZ0kCnp3epLtvP4z8OUg.R2svDxDvQSJV5ZWWIWYnwGnLN4efRxZZ7y3BU2R3ihkg.JPEG.catsisland_sb%2FIMG_5576.JPG&type=sc960_832'
html_url = 'http://google.com'

# 다운받을 경로
save_path1 = 'D:/test1.jpg'
save_path2 = "D:/index.html"

#예외처리
try:
    file1, header1 = req.urlretrieve(img_url, save_path1)
    file2, header2 = req.urlretrieve(html_url, save_path2)

except Exception as e:
    print('Download failed')
    print(e) # 에러 출력

else:
    print(header1)
    print(header2)

    print('Filename1 {}'.format(file1))
    print('Filename2 {}'.format(file2))
    print()

    print('Download Succeed')

 

# urlopen 활용하기

- response는 객체가 되어 response로 함수 실행이 가능하다

import urllib.request as req
from urllib.error import URLError, HTTPError  # 오류방지 위한 라이브러리

# 다운로드 경로 및 파일 명
path_list = ["D:/test1.jpg", "D:/index.html"]

# 다운로드 resource url
target_url = ["https://search.pstatic.net/common/?src=http%3A%2F%2Fblogfiles.naver.net%2FMjAyMTExMTZfMjYg%2FMDAxNjM3MDIwOTUwMDM1.N2KX-bVs9uW85ssnm0wc5P-SGSTgEIWoB-siNT5ztNAg.QaEBAjla0p5cCjU6whCcwPO0tpv6A2fACVv4eDpNhzog.PNG.sooamc%2F1_%25284%2529.png&type=sc960_832","http://google.com"]

for i, url in enumerate(target_url):
    try:
        # 웹 수신 정보 읽기
        response = req.urlopen(url)

        # 수신내용
        contents = response.read()

        print("----------------------------------")

        # 상태정보 중간출력
        print('Header Info-{} : {}'.format(i, response.info()))
        print('HHTP Status Code :{} '.format(response.getcode()))

        with open(path_list[i],'wb') as c:
            c.write(contents)



    except HTTPError as e:
        print("Download fail..")
        print("HTTPerror code : ",e.code)

    except URLError as e:
        print("Download failed")
        print("URL Error reason : ", e.reason )

    else:
        print()
        print("Download Succed..")