[Python] 30. [Scraping] XKCD.com 이미지 다운받기 -- CHECK CHECK CHECK CHECK CHECK

2017. 8. 16. 11:21·빅데이터 프로그래밍/Python
728x90
반응형

[01] https://xkcd.com 이미지 다운받기

1. Rquests 패키지 설치하기

 
C:\Users\soldesk>pip install requests

Collecting requests
  Downloading requests-2.13.0-py2.py3-none-any.whl (584kB)
    100% ■■■■■■■■■ 593kB 1.2MB/s
Installing collected packages: requests
Successfully installed requests-2.13.0

 
1. 이미지 다운로드
[실행 화면]
▷ crawler1.xkcd.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-

import requests, os, bs4

# http://xkcd.com/# 으로 끝나면 마지막 페이지임을 나타냄.
url    = 'http://xkcd.com'                 # starting url

# makedirs: 상위 경로도 함께 생성
# exist_ok=True:  폴더가 있으면 다시 만들지 않고 에러 발생 안됨.
# 선언을 생략하면 기존에 폴더가 있는 경우 에러가 발생됨.
os.makedirs('xkcd', exist_ok=True)    # store comics in ./xkcd
max_download = 0

while not url.endswith('#'): # url '#'으로 끝나지 않을 동안 순환
    max_download +=1
    if max_download >= 11:
        break  # 10장의 이미지 다운로드 후 while 종료
    
    # Download the page.
    print('Downloading page %s'  %url)
    res = requests.get(url)
    res.raise_for_status() # 200 OK 코드가 아닌 경우 에러 발생
    
    # res.text: 내용 추출
    bs = bs4.BeautifulSoup(res.text, 'lxml', from_encoding='utf-8')

    # Find the url of the comic image.
    # <div id="comic">
    #   <img src="//imgs.xkcd.com/comics/geochronology.png"
 # title="'The mountains near here formed when the ... Newfoundland ... 
 # microplate collided with, uhh ... Labrador.' 'Ok, now you're definitely just naming dogs.' 
 #'Wait, no, that's actually almost correct.'"
 # alt="Geochronology" srcset="//imgs.xkcd.com/comics/geochronology_2x.png 2x"> 

    comicElem = bs.select('#comic img')
    if comicElem == []:  # list가 비었는경우, 태그가 없다면
        print('태그가 발견되지 않았습니다.')
    else:
        # comicElem[0]: 첫번째 list 요소인 img 태그의 src 속성을 찾아 
        comicURL = comicElem[0].get('src').strip('//')  # // 없앰
        # Download the image.
        print('Downloading images %s... '  %(comicURL))
        res = requests.get('http://' + comicURL)
        res.raise_for_status()

        # ./xkcd 폴더에 이미지 저장
        # os.path.basename(comicURL): 순수 이미지명만 추출
        # os.path.join('xkcd', 파일명): /xkcd/파일명의 형태로 조합
        imageFile = open(os.path.join('xkcd', os.path.basename(comicURL)), 'wb')
        for chunk in res.iter_content(100000):  # 100,000 바이트씩 기록
            imageFile.write(chunk)                   # 파일 기록
        imageFile.close()                               # 파일 닫기

    # 이전 주소로 이동
    # <a rel="prev" href="/1828/" accesskey="p">Prev</a>
    prevLink = bs.select('a[rel="prev"]')[0]  
    # href 속성의 값 --> http://xkcd.com/1828 산출
    url = 'http://xkcd.com' + prevLink.get('href') 
    
print('실행 종료')




-------------------------------------------------------------------------------------
 

[실습] 자신의 다음 블로그 article에서 이미지를 모두 다운받는 프로그램을 제작하세요.
<img src="https://t1.daumcdn.net/cfile/blog/2223594F58FA34B322" class="txc-image"....

nameList = bsObj.findAll("img", {"class":"txc-image"})

▷ crawler1.daum_blog.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-

import requests, os, bs4

# 다음 블로그
url    = 'http://blog.daum.net' 
os.makedirs('daum_blog', exist_ok=True) 

res = requests.get(url)
res.raise_for_status() # 200 OK 코드가 아닌 경우 에러 발생
    
# res.text: 내용 추출
bs = bs4.BeautifulSoup(res.text, 'lxml', from_encoding='utf-8')

tags = bs('div', {'class': 'cont_post'})
print(type(tags))  # <class 'bs4.element.ResultSet'>
print(tags)  # list
print('갯수: ' + str(len(tags)))
print('------------------------------------------------------')        

for item in tags:
    print(item.getText())


print('실행 종료')





-------------------------------------------------------------------------------------

 

 

 

728x90
반응형

'빅데이터 프로그래밍 > Python' 카테고리의 다른 글

[Python] 32. [MySql] 데이터베이스 개론, MySQL 5.6 Potable(개발자 유형) 설치, 한글 깨짐, 처리, 보관, 수정, 삭제  (0) 2017.08.21
[Python] 31. [Scraping] Selenium 모듈을 이용한 폼과 로그인 인증 통과 테스트  (0) 2017.08.16
[Python] 29. [Scraping] KoNLPy 자연어 처리 패키지, JPype 설치, 명사 분리 추출 후, 단어 사용 빈도 계산하기  (0) 2017.08.16
[Python] 28. [Scraping] 한겨레 신문 뉴스, Naver 뉴스, 동아 일보 뉴스 검색 drawling  (1) 2017.08.16
[Python] 27. [Scraping] Web Scraping 기초, 한글 처리, BeautifulSoup 설치, 기본 트리 운행, 정규 표현식 이용  (0) 2017.08.05
'빅데이터 프로그래밍/Python' 카테고리의 다른 글
  • [Python] 32. [MySql] 데이터베이스 개론, MySQL 5.6 Potable(개발자 유형) 설치, 한글 깨짐, 처리, 보관, 수정, 삭제
  • [Python] 31. [Scraping] Selenium 모듈을 이용한 폼과 로그인 인증 통과 테스트
  • [Python] 29. [Scraping] KoNLPy 자연어 처리 패키지, JPype 설치, 명사 분리 추출 후, 단어 사용 빈도 계산하기
  • [Python] 28. [Scraping] 한겨레 신문 뉴스, Naver 뉴스, 동아 일보 뉴스 검색 drawling
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    프런트엔드
    브라우저 자동화
    nginx ssl 적용
    lang rust
    오류
    Extension Bisect
    gitlab 설치
    rust linux
    nginx ssl 설정
    nginx
    proxy pass
    Rust lang
    AI 코딩 에이전트
    css transition
    spring java
    자바 객체 지향
    servlet class
    자바 생성자
    ubuntu
    자바 배열
    jsp include
    에디터 팁
    css perspective
    mysql db
    vscode
    React Compiler
    vue cli
    docker
    css table
    러스트
    자바 exception
    jsp parameter
    자바 for문
    vue 설치
    css list
    자바 클래스
    VS Code 팁
    클론코딩
    티스토리 자동화
    ssl 인증서 발급
    css tb
    svelte
    SSL 인증서
    css block
    리눅스 설치
    Java Array
    css float
    java casting
    API 설계
    Node
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[Python] 30. [Scraping] XKCD.com 이미지 다운받기 -- CHECK CHECK CHECK CHECK CHECK
상단으로

티스토리툴바