코딩정보




● 완전 쉽게 파이썬으로 텍스트 및 이미지 크롤링하기

♨ 카랜더 일정 : 2021년11월19일
  • 링크

  • 첨부

  • 컨텐츠 정보

    본문

    ● 완전 쉽게 파이썬으로 텍스트 및 이미지 크롤링하기 | 수익형 웹, 앱 만들기 1강


    수익화까지 할 수 있는 완성형 웹, 앱 서비스, 인공지능이 보는 나의 동물상 테스트 만들기 1강으로 인공지능 학습에 필요한 동물상 연예인 사진 데이터를 수집하기 위한 파이썬 크롤링 기초 강의입니다. Beautifulsoup를 활용하여 네이버 실시간 검색 순위를 크롤링하여 텍스트 파일로 저장해보고, google-images-download를 활용하여 코드 1줄만 수정하고도 연예인 사진을 다운받는 실습을 해봅니다. 파이썬과 라이브러리의 개념을 잘 모르셔도 따라 하실 수 있게 기초부터 차근차근 설명해 드립니다. 이처럼 잘되어있는 라이브러리와 예제 코드를 활용한다면 코드 1줄만 수정하여도 원하는 로직을 작성하실 수 있습니다. - 구름IDE https://ide.goorm.io/ - Beautifulsoup 공식 문서 https://www.crummy.com/software/Beaut... - google-images-download pypi https://pypi.org/project/google_image... - 완성 코드 보기 https://github.com/youtube-jocoding/p... [※ 네이버/구글 업데이트로 실시간 검색어 크롤링이 현재 영상 속 방법으로는 불가능해졌습니다 ※] 1. 네이버 검색 순위 크롤링 원래는 urlopen을 수행할때 검색어가 포함되어 있어서 바로 가져오면 됐지만, 이제는 페이지를 다 로딩한 후 검색어를 동적으로 불러오니 위의 코드로 가져오는 것은 불가능합니다. 셀레니움등 추가 도구를 사용해야하는데 관련 내용은 아래 영상을 참고해주세요! 셀레니움 구글 이미지 크롤링(네이버 실검 크롤링도 가능): https://youtu.be/1b7pXC1-IbE 영상 속 방법으로는 현재 zum은 문제 없이 동작하니 줌에서 연습해보시는 것도 좋을 것 같습니다. 줌 홈페이지 : https://m.zum.com/#!/home 2. 구글 이미지 크롤링 구글 검색에서도 최근 업데이트가 있어 라이브러리가 잠시 막혀서 Selenium을 활용한 버전으로 영상을 추가 제작하였습니다! 아래 영상을 참고해주세요! 셀레니움 구글 이미지 크롤링: https://youtu.be/1b7pXC1-IbE 라이브러리 관련 이슈는 링크를 통해 확인해주시기 바랍니다. https://github.com/hardikvasa/google-... --- 본 영상은 구름IDE에서 에반젤리스트 활동 지원을 받아 제작되었습니다.

    ===========

    2번째 영상 정보

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

    이번 영상은 파이썬으로 셀레니움(selenium)을 활용하여 구글에서 이미지 크롤링을 하는 방법을 알려드립니다. 단순한 이미지 크롤링이 아닌 응용하면 웹 브라우저로 할 수 있는 모든 업무를 다 자동화 할 수 있습니다. 

    파이썬 가상환경 생성부터 크롬 브라우저 드라이버 다운로드 등 기초 세팅 과정부터 차근차근 알려드립니다. 직접 실습해보시고 다른 업무 자동화에 응용해보세요!

    사람이 브라우저를 통해서 확인하는 것과 같은 방식이여서 이전 영상처럼 업데이트가 되어도 막히지 않고 계속 응용하여 활용하실 수 있습니다.


    파이썬 및 코드 에디터가 설치가 안되신 분들은 이전 파이썬 강의 1강을 참고해주세요!

    https://youtu.be/yytWGELNeOI



    완성된 코드

    https://github.com/youtube-jocoding/python-selenium-google-image-crawling/blob/master/google.py



    이미지를 다운로드 하실때 나무위키 등 특정 사이트의 경우 봇이 접근하는 것을 차단해서 urllib.request.urlretrieve(imgUrl, "test.jpg") 줄에서

     urllib.error.HTTPError: HTTP Error 403: Forbidden가 뜨실 수 있습니다. 그럴때는 아래와 같이 브라우저 인것 처럼 속이는 header를 추가하시면 정상적으로 크롤링 할 수 있습니다!


    opener=urllib.request.build_opener()

    opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]

    urllib.request.install_opener(opener)

    urllib.request.urlretrieve(imgUrl, "test.jpg")


    #파이썬 #크롤링 #셀레니움


    00:00 하이라이트

    00:20 인트로

    00:29 수업 소개

    01:00 셀레니움의 개념

    1:56 목차

    2:15 파이썬 가상 환경 세팅

    4:59 Selenium 설치 및 브라우저 세팅

    6:31 구글 이미지 크롤링 코드 작성

    31:22 셀레니움 네이버 실시간 검색어 크롤링 방법 소개

    31:49 아웃트로



    강의 소스정보

    https://github.com/youtube-jocoding/python-selenium-google-image-crawling/blob/master/google.py

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

    영상 참조 작업

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


    관리자로 POWERSHELL 실행  .\activate 실행시 

    PS K:\photo_data\python> cd .\selenium\
    PS K:\photo_data\python\selenium> cd .\Scripts\
    PS K:\photo_data\python\selenium\Scripts> .\activate
    .\activate : 이 시스템에서 스크립트를 실행할 수 없으므로 K:\photo_data\python\selenium\Scripts\Activate.ps1 파일을 로드
    할 수 없습니다
    . 자세한 내용은 about_Execution_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.
    위치 줄:1 문자:1
    + .\activate
    + ~~~~~~~~~~
        + CategoryInfo          : 보안 오류: (:) [], PSSecurityException
        + FullyQualifiedErrorId : UnauthorizedAccess
    PS K:\photo_data\python\selenium\Scripts> Set-ExecutionPolicy Unrestricted
    PS K:\photo_data\python\selenium\Scripts> Get-ExecutionPolicy
    Unrestricted
    PS K:\photo_data\python\selenium\Scripts> ls


        디렉터리: K:\photo_data\python\selenium\Scripts


    Mode                LastWriteTime        Length Name
    ----                -------------        ------ ----
    d-----      2021-11-19  오후 10:13                selenium
    -a----      2021-11-19  오후 9:43          1978 activate
    -a----      2021-11-19  오후 9:43            970 activate.bat
    -a----      2021-11-19  오후 9:43          19408 Activate.ps1
    -a----      2021-11-19  오후 9:53      11372032 chromedriver.exe
    -a----      2021-11-19  오후 9:43            368 deactivate.bat
    -a----      2021-11-19  오후 9:43        106359 pip.exe
    -a----      2021-11-19  오후 9:43        106359 pip3.9.exe
    -a----      2021-11-19  오후 9:43        106359 pip3.exe
    -a----      2021-11-19  오후 9:42        543464 python.exe
    -a----      2021-11-19  오후 9:42        542440 pythonw.exe
    -a----      2021-11-19  오후 9:42        711680 pythonw_d.exe
    -a----      2021-11-19  오후 9:42        713216 python_d.exe
    -a----      2021-11-19  오후 10:05            243 test.py


    PS K:\photo_data\python\selenium\Scripts> .\activate.ps1
    (selenium) PS K:\photo_data\python\selenium\Scripts> deactivate
    PS K:\photo_data\python\selenium\Scripts> .\activate.ps1
    (selenium) PS K:\photo_data\python\selenium\Scripts> deactivate
    PS K:\photo_data\python\selenium\Scripts> .\activate
    (selenium) PS K:\photo_data\python\selenium\Scripts>
    ======================

    Winget을 사용하여 PowerShell 설치

    Windows에 PowerShell 설치 - PowerShell | Microsoft Docs

    winget search Microsoft.PowerShell
    winget install --id Microsoft.Powershell --source winget
    winget install --id Microsoft.Powershell.Preview --source winget

    ============

    3232235521_1637345445.4673.png

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    import urllib.request


    opener=urllib.request.build_opener()
    opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]




    # plusUrl1 = input('구글검색 주소입력: ')
    plusUrl2 = input('구글이미지 사진저장 검색어입력(세계관광명소고화질): ')

    driver = webdriver.Chrome()
    driver.get("https://www.google.co.kr/imghp?hl=ko&ogbl")
    # driver.get(plusUrl1)
    elem = driver.find_element_by_name("q")
    # elem.send_keys("배우사진")
    elem.send_keys(plusUrl2)
    elem.send_keys(Keys.RETURN)

    SCROLL_PAUSE_TIME = 1

    # python selenium scroll down
    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            try:
                driver.find_element_by_css_selector("mye4qd").click()
            except:
                break
        last_height = new_height
       

    images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
    count = 1
    for image in images:
        try:
            image.click()
            time.sleep(2)
            imgUrl=driver.find_element_by_xpath("/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[2]/div/a/img").get_attribute("src")
            urllib.request.install_opener(opener)
            # urllib.request.urlretrieve(imgUrl, "test.jpg")
            # urllib.request.urlretrieve(imgUrl, plusUrl2 + str(count) + ".jpg")
            urllib.request.urlretrieve(imgUrl, plusUrl2 + str(count) + ".jpg")
            count =count + 1
        except:
            pass
       
    driver.close()
     


    작업한 갤러리 그글 검색 사진 입니다.

    https://11q.kr/piwigo/index.php?/category/797

    3232235521_1637388023.1386.png

    3232235521_1637388153.268.png

    3232235521_1637388198.2724.png

     https://11q.kr 에 등록된 자료 입니다. ♠ 정보찾아 공유 드리며 출처는 링크 참조 바랍니다♠1.png

    [ 추가 정보 ... 더보기) ]
    뷰PDF 1,2



    office view

    관련자료

    댓글목록

    profile_image

    11qkr님의 댓글

    11qkr 쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 아이피 (192.♡.0.1) 작성일

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    import urllib.request

    driver = webdriver.Chrome()
    driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&authuser=0&ogbl")
    elem = driver.find_element_by_name("q")
    elem.send_keys("조코딩")
    elem.send_keys(Keys.RETURN)

    SCROLL_PAUSE_TIME = 1
    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)
        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            try:
                driver.find_element_by_css_selector(".mye4qd").click()
            except:
                break
        last_height = new_height

    images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
    count = 1
    for image in images:
        try:
            image.click()
            time.sleep(2)
            imgUrl = driver.find_element_by_xpath('/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div[1]/div[1]/div/div[2]/a/img').get_attribute("src")
            opener=urllib.request.build_opener()
            opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
            urllib.request.install_opener(opener)
            urllib.request.urlretrieve(imgUrl, str(count) + ".jpg")
            count = count + 1
        except:
            pass

    driver.close()

    답변
    profile_image

    11qkr님의 댓글

    11qkr 쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 아이피 (192.♡.0.1) 작성일

    관리자로 POWERSHELL 실행
    PS K:\photo_data\python> cd .\selenium\
    PS K:\photo_data\python\selenium> cd .\Scripts\
    PS K:\photo_data\python\selenium\Scripts> .\activate
    .\activate : 이 시스템에서 스크립트를 실행할 수 없으므로 K:\photo_data\python\selenium\Scripts\Activate.ps1 파일을 로드
    할 수 없습니다. 자세한 내용은 about_Execution_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.
    위치 줄:1 문자:1
    + .\activate
    + ~~~~~~~~~~
        + CategoryInfo          : 보안 오류: (:) [], PSSecurityException
        + FullyQualifiedErrorId : UnauthorizedAccess
    PS K:\photo_data\python\selenium\Scripts> Set-ExecutionPolicy Unrestricted
    PS K:\photo_data\python\selenium\Scripts> Get-ExecutionPolicy
    Unrestricted
    PS K:\photo_data\python\selenium\Scripts> ls


        디렉터리: K:\photo_data\python\selenium\Scripts


    Mode                LastWriteTime        Length Name
    ----                -------------        ------ ----
    d-----      2021-11-19  오후 10:13                selenium
    -a----      2021-11-19  오후 9:43          1978 activate
    -a----      2021-11-19  오후 9:43            970 activate.bat
    -a----      2021-11-19  오후 9:43          19408 Activate.ps1
    -a----      2021-11-19  오후 9:53      11372032 chromedriver.exe
    -a----      2021-11-19  오후 9:43            368 deactivate.bat
    -a----      2021-11-19  오후 9:43        106359 pip.exe
    -a----      2021-11-19  오후 9:43        106359 pip3.9.exe
    -a----      2021-11-19  오후 9:43        106359 pip3.exe
    -a----      2021-11-19  오후 9:42        543464 python.exe
    -a----      2021-11-19  오후 9:42        542440 pythonw.exe
    -a----      2021-11-19  오후 9:42        711680 pythonw_d.exe
    -a----      2021-11-19  오후 9:42        713216 python_d.exe
    -a----      2021-11-19  오후 10:05            243 test.py


    PS K:\photo_data\python\selenium\Scripts> .\activate.ps1
    (selenium) PS K:\photo_data\python\selenium\Scripts> deactivate
    PS K:\photo_data\python\selenium\Scripts> .\activate.ps1
    (selenium) PS K:\photo_data\python\selenium\Scripts> deactivate
    PS K:\photo_data\python\selenium\Scripts> .\activate
    (selenium) PS K:\photo_data\python\selenium\Scripts>

    답변
    profile_image

    11qkr님의 댓글

    11qkr 쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 아이피 (192.♡.0.1) 작성일
    답변
    profile_image

    11qkr님의 댓글

    11qkr 쪽지보내기 메일보내기 홈페이지 자기소개 아이디로 검색 전체게시물 아이피 (192.♡.0.1) 작성일

    구글링 검색 배우사진  376장 최신 검색 파이션
    ===========
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    import urllib.request

    driver = webdriver.Chrome()
    driver.get("https://www.google.co.kr/imghp?hl=ko&ogbl")
    elem = driver.find_element_by_name("q")
    elem.send_keys("배우사진")
    elem.send_keys(Keys.RETURN)

    SCROLL_PAUSE_TIME = 1

    # python selenium scroll down
    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            try:
                driver.find_element_by_css_selector("mye4qd").click()
            except:
                break
        last_height = new_height
       

    images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
    count = 1
    for image in images:
        try:
            image.click()
            time.sleep(2)
            imgUrl=driver.find_element_by_xpath("/html/body/div[2]/c-wiz/div[3]/div[2]/div[3]/div/div/div[3]/div[2]/c-wiz/div/div[1]/div[1]/div[2]/div/a/img").get_attribute("src")
            urllib.request.urlretrieve(imgUrl, str(count) + "_actor_photo.jpg")
            count =count + 1
        except:
            pass
       
    driver.close()
     ================

    답변



    ♥간단_메모글♥


    최근글


    새댓글



    PHP 안에 HTML ☞ 홈페이지 화면갱신 시간은 ♨
    ▶ 2024-04-19 17:51:39

    오늘의 홈 현황


    • 현재 접속자♨ 185(1) 명
    • 오늘 가입자※ 2 명
    • 어제 가입자※ 7 명
    • 주간 가입자※ 16 명
    • 오늘 방문자 1,912 명
    • 어제 방문자 2,103 명
    • 최대 방문자 13,042 명
    • 전체 방문자 4,278,570 명
    • 전체 게시물※ 8,522 개
    • 전체 댓글수※ 24,482 개
    • 전체 회원수 10,912 명

    QR코드


    ☞ 사진기로 촬영하시면 방문링크 됩니다

    알림 0








    최신글↑