'Python' 카테고리의 다른 글

[Python] konlpy 형태소 분석  (0) 2024.03.22
[Python] 판다스 Pandas  (1) 2024.03.21
[Python] 유튜브 크롤링(2)  (0) 2024.03.20
[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] Selenium 소개 및 사용법  (0) 2024.03.18

'Python' 카테고리의 다른 글

오늘의 블로그  (0) 2024.04.03
[Python] 판다스 Pandas  (1) 2024.03.21
[Python] 유튜브 크롤링(2)  (0) 2024.03.20
[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] Selenium 소개 및 사용법  (0) 2024.03.18

ch21 판다스 라이브러리 소개 및 활용

<aside> 💡 이번 차시의 학습목표

✔ 판다스 기본 기능 이해

✔ 시리즈, 데이터프레임 기초 문법 이해

</aside>

01. pandas란

  1. 데이터 조작 및 분석을 위한 라이브러리
  2. 데이터과학의 많은 부분을 처리할 수 있으며 최적화된 도구
  3. 쉼표로 구분된 값, JSON, Excel과 같은 다양한 파일 형식에서 데이터를 가져올 수 있음
  4. 데이터를 표 형태로 다룰 수 있으며, pandas에서 제공하는 데이터의 종류는 다음과 같음
    1. 시리즈(Series)
      1. 1차원 배열과 같은 자료 구조
      2. 파이썬의 리스트 자료형과 비슷하지만 인덱스 값을 직접 지정할 수 있는 특징이 있음
      3. Series끼리의 연산시 인덱스를 기준으로 연산도 가능
    2. 데이터 프레임(DataFrame)
      1. 행(row), 열(column)로 이루어진 2차원 데이터 구조를 다룸
      2. 엑셀 또는 데이터베이스의 표(table)와 유사한 구조
      3. 각 열 데이터는 Series이며, DataFrame은 Series의 집합
      4. DataFrame 구조(공식홈페이지)
  5. 공식 홈페이지
    1. 🌐 https://pandas.pydata.org/
  6. 이름 유래
    1. PANel DAta라는 경제학 용어에서 가져온 말이며, 동물 팬더와는 관련 없음

02. pandas 설치 및 사용 방법

  1. pip install을 이용하여 모듈을 설치하고 사용해야 함. 사용시에는 일반적으로 pd로 줄여서 사용함.
    # 설치
    >> pip install pandas
    
    # 사용
    import pandas as pd

03. pandas 다뤄보기

  1. 시리즈(Series)
    1. 국어, 영어, 수학 성적을 다루는 시리즈
    2. 국어성적 시리즈 선언
      1. 시리즈 선언 시 pd.Series() 사용
        1. Series(담을데이터, 인덱스 값(생략시 0부터 순차값 생성))
          score_korean = pd.Series([98, 76, 60, 85, 80])
          print(score_korean)
    3. 인덱스 지정하여 시리즈 선언하기
      1. 인덱스 값을 1~5까지의 학번 데이터로 지정
        score_korean = pd.Series([98, 76, 60, 85, 80], index=[1, 2, 3, 4, 5])
        print(score_korean)
      2. range 함수 적용
        score_korean = pd.Series([98, 76, 60, 85, 80], index=range(1,6))
        print(score_korean)
    4. 학번 데이터를 따로 선언하여 영어, 수학 점수에도 활용
      student_number = [1, 2, 3, 4, 5]
    5. 성적 데이터도 따로 리스트로 선언하여 적용 가능
      korean_list = [98, 76, 60, 85, 80]
      score_korean = pd.Series([98, 76, 60, 85, 80], index=student_number)
    6. 영어 성적 시리즈 선언
      english_list = [88, 92, 100, 55, 70]
      score_english = pd.Series(english_list, index=student_number)
    7. 국어, 영어 성적 합계
      1. 시리즈 간의 연산도 가능하며 인덱스끼리 값을 계산함
        total = score_korean + score_english
    8. 수학 성적 시리즈 선언
      1. 학번은 1~5번 이지만 순서가 다른 경우
        score_math = pd.Series([30, 20, 10, 40, 50], index=[3, 2, 1, 4, 5])
      2. 인덱스 순으로 정렬하여 출력할 때는 sort_values()를 사용하며, 매개값으로 정렬 기준을 넘김
        print(score_math.sort_index())
    9. 전체 성적 합계
      1. 수학 성적 시리즈를 만들 때 인덱스 순서는 달랐지만 계산시에는 인덱스끼리 계산을 하기 때문에 학번별로 성적 합산이 됨
        total = score_korean + score_english + score_math
      2. 인덱스, 값 기준으로 정렬하여 출력하기
        # 인덱스 기준 오름차순 정렬
        print(total.sort_index())
        # 인덱스 기준 내림차순 정렬
        print(total.sort_index(ascending=False))
        # 값 기준 오름차순 정렬
        print(total.sort_values())
        # 값 기준 내림차수 정렬
        print(total.sort_values(ascending=False))

 

03-1. 실습 예제

📥실습 코드

ex01_pandas_01.py

import pandas as pd

# Series 생성 
# 국어성적 정보
score_korean = pd.Series([98, 76, 60, 85, 80])
print(score_korean)

# 인덱스를 지정하여 Series 생성
score_korean = pd.Series([98, 76, 60, 85, 80], index=[1, 2, 3, 4, 5])
print(score_korean)

# range 함수 활용
score_korean = pd.Series([98, 76, 60, 85, 80], index=range(1,6))
print(score_korean)

# index 값 따로 선언 후 활용
student_number = [1, 2, 3, 4, 5]
score_korean = pd.Series([98, 76, 60, 85, 80], index=student_number)
print(score_korean)

# 성적 데이터도 리스트로 선언하여 활용 가능
korean_list = [98, 76, 60, 85, 80]
score_korean = pd.Series(korean_list, index=student_number)
print(score_korean)

# 영어 성적 추가 
english_list = [88, 92, 100, 55, 70]
score_english = pd.Series(english_list, index=student_number)
print(score_english)

# 국어, 영어 학생별 성적 합산 
total = score_korean + score_english
print(total)

# 수학 성적 추가(인덱스 번호가 1~5로 순차적이지 않음)
score_math = pd.Series([30, 20, 10, 40, 50], index=[3, 2, 1, 4, 5])
print(score_math)
print(score_math.sort_index())

# 전체 성적 합산(pandas가 인덱스 별로 계산을 수행함)
total = score_korean + score_english + score_math
print(total)

# 인덱스 기준 오름차순 정렬
print(total.sort_index())
# 인덱스 기준 내림차순 정렬
print(total.sort_index(ascending=False))
# 값 기준 오름차순 정렬
print(total.sort_values())
# 값 기준 내림차순 정렬
print(total.sort_values(ascending=False))

04. 데이터프레임 다뤄보기

  1. 데이터프레임은 아래와 같은 표 형태의 2차원 데이터를 다룰 수 있으며, 시리즈로 다뤄본 성적데이터를 코드로 구현학번 이름 국어 영어 수학
    1 김파이 96 88 10
    2 이파이 76 92 20
    3 박파이 60 100 30
    4 최파이 85 55 40
    5 정파이 80 70 50
  2. 데이터프레임 선언
    1. 데이터프레임 선언시 pd.DataFrame() 사용
    2. 문법
      pd.DataFrame(저장할데이터)
  3. 성적 데이터 입력해보기
    1. 과목별 점수를 리스트 단위로 입력 후 출력
      ex02_panda_series_01.py
      
      import pandas as pd
      
      scores = pd.DataFrame([
          [96, 76, 60, 85, 80], [88, 92, 100, 55, 70], [10, 20, 30, 40, 50]
      ])
      print(scores)
    2. 학생별 점수를 리스트 단위로 입력 후 출력
      ex02_panda_dataframe_01.py
      
      import pandas as pd
      
      scores = pd.DataFrame([
          [96, 88, 10], [76, 92, 20], [60, 100, 30], [85, 55, 40], [80, 70, 50]
      ])
      print(scores)
    3. 인덱스를 적용하여 데이터프레임 선언
      ex02_panda_dataframe_02.py
      
      import pandas as pd
      
      scores = pd.DataFrame([
          [96, 76, 60, 85, 80], [88, 92, 100, 55, 70], [10, 20, 30, 40, 50]
      ], index=["국어", "영어", "수학"])
      print(scores)
      
      scores = pd.DataFrame([
          [96, 88, 10], [76, 92, 20], [60, 100, 30], [85, 55, 40], [80, 70, 50]
      ], index=[1, 2, 3, 4, 5])
      print(scores)
    4. 컬럼명을 각각 지정하여 선언하기
      ex02_panda_dataframe_03.py
      
      import pandas as pd
      
      scores = pd.DataFrame(
          {
              "국어": [96, 76, 60, 85, 80],
              "영어": [88, 92, 100, 55, 70],
              "수학": [10, 20, 30, 40, 50]
          }, index=[1, 2, 3, 4, 5]
      )
      print(scores)
    5. 딕셔너리를 데이터프레임으로 변환해보기
      ex02_panda_dataframe_04.py
      
      import pandas as pd
      
      scores_dict = {"국어": [96, 76, 60, 85, 80],
                      "영어": [88, 92, 100, 55, 70],
                      "수학": [10, 20, 30, 40, 50]}
      
      scores = pd.DataFrame(scores_dict)
      print(scores)
      
      # 인덱스 지정
      scores = pd.DataFrame(scores_dict, index=[1, 2, 3, 4, 5])
      print(scores)
  4. 데이터프레임에 데이터 추가하기
    1. 이름 열 추가하기
      1. 문법
        데이터프레임이름[”추가할 열이름”] = 추가할데이터
      2. 데이터를 하나만 지정하는 경우
        scores["이름"] = "김파이"
      3. 데이터를 모두 지정하는 경우
        scores["이름"] = ["김파이", "이파이", "박파이", "최파이", "정파이"]
      4. 실습 코드
        ex02_panda_dataframe_05.py
        
        import pandas as pd
        
        scores = pd.DataFrame(
            {
                "국어": [96, 76, 60, 85, 80],
                "영어": [88, 92, 100, 55, 70],
                "수학": [10, 20, 30, 40, 50]
            }, index=[1, 2, 3, 4, 5]
        )
        print(scores)
        
        # 데이터 하나만 지정
        # scores["이름"] = "김파이"
        # 데이터 모두 지정
        scores["이름"] = ["김파이", "이파이", "박파이", "최파이", "정파이"]
        print(scores)
    2. 학생 행 추가하기
      1. 문법
        데이터프레임이름.loc['인덱스값'] = 추가할데이터
      2. 데이터를 하나만 지정하는 경우
        scores.loc[6] = 100
      3. 데이터를 모두 지정하는 경우
        scores.loc[6] = [100, 100, 100, "조파이"]
      4. 실습 코드
        ex02_panda_dataframe_06.py
        
        import pandas as pd
        
        scores = pd.DataFrame(
            {
                "국어": [96, 76, 60, 85, 80],
                "영어": [88, 92, 100, 55, 70],
                "수학": [10, 20, 30, 40, 50],
                "이름": ["김파이", "이파이", "박파이", "최파이", "정파이"]
            }, index=[1, 2, 3, 4, 5]
        )
        print(scores)
        
        # scores.loc[6] = 100
        scores.loc[6] = [100, 100, 100, "조파이"]
        print(scores)

 

05. 데이터 프레임 주요 method

  1. 성적 데이터프레임 준비

    scores = pd.DataFrame(
        {
            "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
            "국어": [96, 76, 60, 85, 80, 100],
            "영어": [88, 92, 100, 55, 70, 100],
            "수학": [10, 20, 30, 40, 50, 100],
        }, index=[1, 2, 3, 4, 5, 6]
    )
  2. transpose()
    1. 행, 열을 서로 맞바꿈
      ex03_pandas_method_01.py
      
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      )
      print(scores)
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      ).transpose()
      print(scores)
  3. sort_index()
    1. index 기준으로 정렬
    2. 매개변수로 내림차순, 오름차순을 지정할 수 있음(기본은 오름차순)
      ex03_pandas_method_02.py
      
      import pandas as pd
      
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      )
      print(scores.sort_index())
      # index 기준 오름차순 정렬
      print(scores.sort_index(ascending=True))
      # index 기준 내림차순 정렬
      print(scores.sort_index(ascending=False))
  4. sort_values()
    1. 값 기준으로 정렬
    2. 기준 열, 내림차순/오름차순에 대한 설정 가능
      ex03_pandas_method_03.py
      
      import pandas as pd
      
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      )
      print(scores)
      # 이름 기준 오름차순 정렬
      print(scores.sort_values(by="이름", ascending=True))
      # 이름 기준 내림차순 정렬
      print(scores.sort_values(by="이름", ascending=False))
      # 수학 기준 오름차순 정렬
      print(scores.sort_values(by="수학", ascending=True))
  5. head(), tail()
    1. 조회할 줄 수 지정하여 첫줄 또는 마지막줄 부터 숫자만큼 조회
      ex03_pandas_method_04.py
      
      import pandas as pd
      
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      )
      print(scores)
      # 처음 2줄만 조회
      print(scores.head(2))
      # 마지막 2줄만 조회
      print(scores.tail(2))

 

 

06. 데이터프레임 csv파일로 내보내기

  1. csv(comma separated values) 파일
    1. 표 형태의 데이터를 저장하는 파일 형식으로 다양한 분야에서 사용되며, 엑셀과 같은 스프레드시트 프로그램에서 편집이 가능함
  2. 앞 예제에서 사용한 성적정보를 csv파일로 내보내기
    1. 한글 깨짐 방지를 위해 encoding 옵션 필요
      ex04_pandas_csv.py
      
      import pandas as pd
      
      scores = pd.DataFrame(
          {
              "이름": ["김파이", "이파이", "박파이", "최파이", "정파이", "조파이"],
              "국어": [96, 76, 60, 85, 80, 100],
              "영어": [88, 92, 100, 55, 70, 100],
              "수학": [10, 20, 30, 40, 50, 100],
          }, index=[1, 2, 3, 4, 5, 6]
      )
      
      # 현재폴더에 scores.csv 라는 이름으로 파일 생성 
      scores.to_csv("./scores.csv", encoding="utf-8-sig")
    2. 생성된 파일 엑셀에서 열어본 화면

 

 

ch22 판다스로 크롤링 결과 저장하기

💡 이번 차시의 학습목표

✔ 인기급상승 동영상의 제목, 조회수 csv 파일로 저장

✔ 조회수 기준 내림차순으로 정렬하여 저장

01. 인기급상승 동영상 csv 파일로 저장하기

  1. 인기급상승 동영상 크롤링코드 활용
    driver = webdriver.Chrome()
    driver.get("<https://www.youtube.com/feed/trending>")
    time.sleep(2)
    elements = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
    time.sleep(2)
    hits_list = []
    title_list = []
    for element in elements:
        if element.get_attribute("aria-label"):
            hits_text = element.get_attribute("aria-label")
            start_index = hits_text.rfind("조회수")+4
            end_index = hits_text.rfind("회")
            hits = hits_text[start_index:end_index]
            hits = int(hits.replace(",", ""))
            title_list.append(element.text)
            hits_list.append(hits)
        else:
            print("조회수 데이터 없음")​
  2. 제목, 조회수 목록을 딕셔너리에 담기
    crawling_result = {
        "title": title_list,
        "hits": hits_list
    }
dataFrame = pd.DataFrame(title_list)
dataFrame.to_csv("result.csv", encoding="utf-8-sig")
  1. csv 파일 저장 결과(Visual Studio Code에서 실행)
  2. 조회수 내림차순으로 정렬하여 저장하기
    1. 판다스 sort_values() method 활용
      1. by=[”hits”] 로 조회수 기준으로 정렬, ascending=False로 내림차순
      2. 정렬 및 csv저장을 한문장으로 작성
        dataFrame.sort_values(by=["hits"], ascending=False).to_csv("result.csv", encoding="utf-8-sig")
  3. 무한 스크롤 적용하기
    1. 진행 순서
      1. 인기 급상승 페이지 접속
      2. 무한스크롤을 이용하여 전체 영상 로딩
      3. 크롤링 및 제목, 조회수 목록 생성
      4. csv로 저장

 

 

'Python' 카테고리의 다른 글

오늘의 블로그  (0) 2024.04.03
[Python] konlpy 형태소 분석  (0) 2024.03.22
[Python] 유튜브 크롤링(2)  (0) 2024.03.20
[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] Selenium 소개 및 사용법  (0) 2024.03.18

ch17 유튜브 크롤링-스크롤 제어

💡 이번 차시의 학습목표

✔ 현재 창의 높이 확인하기 위한 javascript 문법

✔ 스크롤을 제어하기 위한 javascript 문법

✔ selenium으로 javascript 문법 활용하여 스크롤 제어 하기

 

01. 스크롤 작업의 필요성

  1. 유튜브 홈페이지 또는 검색결과 페이지에는 모든 영상 콘텐츠가 한번에 노출되지 않음
  2. 스크롤을 내리는 과정에서 스크롤바가 페이지의 맨 하단까지 내려가게 되면 약간의 로딩 후 다음 영상 목록이 추가됨
  3. 영상 목록이 더 이상 추가되지 않을 때까지 내리기 위해선 스크롤을 계속해서 내려야 하는 노력과 시간 필요
  4. selenium, javascript 문법을 활용하여 모든 영상의 목록이 나올 때 까지 스크롤할 수 있도록 개발

02. 현재 열려있는 페이지의 높이 확인

  1. 브라우저에서 개발자도구 열고 Console 탭 열기
  2. 아래 코드 입력 후 결과 확인 (출력 숫자값은 다를 수 있음)
    1. 현재 브라우저에 열려 있는 페이지의 높이값을 가져오는 javascript 문법
      document.documentElement.scrollHeight​


  3. 스크롤을 제일 하단으로 내린 뒤 위의 코드 다시 입력 후 확인

 

 

03. selenium으로 페이지 높이 가져오는 내용 구현

  1. execute_script() method
    1. javascript 문법을 실행할 수 있도록 하는 method
    2. 매개값으로 javascript 코드 작성
  2. 페이지 높이 가져오는 문법 적용
    driver.execute_script("document.documentElement.scrollHeight")
  3. 앞의 문장으로는 확인할 수 있는 내용은 없으며, 파이썬 변수로 담아서 print() 수행하기 위한 코드로 수정
    1. return 이 추가된 이유는 javascript 문장을 수행후 반환되는 값을 가져오기 위함
    2. 반환값을 h1 변수에 담고 print()로 확인
      h1 = driver.execute_script("return document.documentElement.scrollHeight") print(h1)

 

 

03-1. 실습 예제

📥실습 코드

ex01_scroll.py

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("<https://www.youtube.com/>")
# driver.execute_script("document.documentElement.scrollHeight")
h1 = driver.execute_script("return document.documentElement.scrollHeight")
print(h1)

04. 스크롤 내리기

  1. 개발자 도구 Console 열기
  2. 스크롤을 제어하기 위한 javascript 문법
    1. 브라우저에 대한 제어가 필요하기 때문에 window 객체 사용
    2. scrollTo(x, y): 지정한 가로(x), 세로(y)위치로 스크롤을 이동시키는 함수
      1. 가로 스크롤은 0으로 고정 시키며, 세로 스크롤 값을 조정
    3. 아래와 같은 값을 console에 입력 후 각각 실행하며 스크롤의 위치 변화 확인
      window.scrollTo(0, 30) 
      window.scrollTo(0, 100) 
      window.scrollTo(0, 1000)
  3. 스크롤을 가장 하단으로 내리기
    1. 현재 열려있는 페이지의 높이만큼 스크롤을 내리도록 함
      1. 세로 값을 현재 열려있는 페이지 높이로 지정
        window.scrollTo(0, document.documentElement.scrollHeight)

05. selenium으로 스크롤 내리기 구현

  1. javascript 문법 사용을 위해 execute_script() 사용
    1. 유튜브 홈페이지 접속 후 페이지 높이 확인 후, 페이지 높이만큼 스크롤을 내리기 위한 함수 실행
      # 처음 페이지 높이 가져오기 
      h1 = driver.execute_script("return document.documentElement.scrollHeight")
      print(h1)
      # 페이지 높이 만큼 스크롤 내리기
      driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
  2. 같은 동작 2번 더 실행 후 콘솔에 출력된 페이지 높이값이 점점 증가하는지 확인
    1. 스크롤을 내리는데에 약간의 로딩시간이 필요하므로 스크롤 내린 뒤 time.sleep 을 활용하여 2초의 대기시간 추가
      # 처음 페이지 높이 가져오기 
      h1 = driver.execute_script("return document.documentElement.scrollHeight")
      print(h1)
      # 페이지 높이 만큼 스크롤 내리기
      driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
      # 약간의 로딩시간
      time.sleep(2)
      # 스크롤을 한 번 내린 뒤의 페이지 높이 가져오기 
      h2 = driver.execute_script("return document.documentElement.scrollHeight")
      print(h2)
      # 두번째 스크롤 내리는 동작
      driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight)")
      time.sleep(2)
      # 두 번 스크롤 내린 뒤의 페이지 높이 가져오기 
      h3 = driver.execute_script("return document.documentElement.scrollHeight")
      print(h3)
      time.sleep(3)

 

 

05-1. 실습 예제

📥실습 코드

ex02_scroll.py

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("<https://www.youtube.com/>")

# 처음 페이지 높이 가져오기 
h1 = driver.execute_script("return document.documentElement.scrollHeight")
print(h1)
# 페이지 높이 만큼 스크롤 내리기
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
# 약간의 로딩시간
time.sleep(2)
# 스크롤을 한 번 내린 뒤의 페이지 높이 가져오기 
h2 = driver.execute_script("return document.documentElement.scrollHeight")
print(h2)
# 두번째 스크롤 내리는 동작
driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight)")
time.sleep(2)
# 두 번 스크롤 내린 뒤의 페이지 높이 가져오기 
h3 = driver.execute_script("return document.documentElement.scrollHeight")
print(h3)
time.sleep(3)
  1.  

ch18 유튜브 크롤링-무한 스크롤

💡 이번 차시의 학습목표

✔ 무한 스크롤을 이용하여 유튜브 영상 목록을 모두 불러옴

✔ 영상의 제목 크롤링

01. 무한 스크롤 동작을 위한 방법

  1. 유튜브 홈페이지 접속 후 모든 영상목록을 보려면 스크롤을 계속해서 내려야 모든 영상을 불러올 수 있음
  2. 하지만 검색어에 따라 영상의 갯수는 다르기 때문에 몇 회를 반복하거나 몇 분 동안 반복하는 방식은 적절하지 않음
  3. 페이지 높이를 확인하는 방식을 이용하여 스크롤 수행하는 절차
    1. 스크롤 수행 전 높이 확인
    2. 스크롤 한 번 수행
    3. 스크롤 수행 후 페이지의 높이와 스크롤 수행 전 페이지의 높이 비교
      1. 스크롤 수행 후의 페이지 높이가 크면 스크롤 수행
      2. 두 값이 일치한다면 스크롤 중단

02. 무한 스크롤 코드 구현하기

  1. 스크롤은 계속 반복적으로 수행되어야 하기 때문에 반복문 활용
    1. 횟수가 정해져 있지 않으므로 while문 활용
    while True:
    	# 반복문 내용
    
  2. 스크롤을 수행하기 전 페이지의 높이 가져오기
  3. before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
  4. 페이지 높이만큼 스크롤 내리기
  5. driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
  6. 스크롤 수행 후 페이지 높이 가져오기
  7. after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
  8. 스크롤 수행 전, 후 페이지 높이 비교
    1. 높이가 동일하면 더이상 스크롤이 내려갈 수 없다 판단하여 while문 종료
    if before_scroll_height == after_scroll_height:
            break
    

02-1. 실습 코드

<aside> 📌 실습코드는 코드박스에서 확인해주세요!

</aside>

  1. 스크롤을 내린 후 2초씩의 대기 시간을 적용함
  2. 모든 스크롤이 내려갔는지 확인을 위해 while문 종료 후 10초의 대기시간 적용

📥실습 코드

ex01_scroll.py

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("<https://www.youtube.com/>")

while True:
    before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
    driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
    time.sleep(2)
    after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
    time.sleep(2)
    if before_scroll_height == after_scroll_height:
        break
    # else:
    #     before_scroll_height = after_scroll_height

time.sleep(10)

03. 스크롤 완료 후 영상의 제목만 가져오기

  1. find_elements() 를 활용하여 제목을 가져온 뒤 for문으로 출력
    1. 제목 가져오는 방법은 이전 차시에서 배웠던 방식과 동일함
    2. 영상 갯수 확인을 위해 len() 함수 활용
    titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
    print("영상 갯수: ", len(titles))
    for title in titles:
        print(title.text)
    

04. 무한 스크롤 코드 함수화하기

  1. 스크롤 부분만 함수로 정의
    ex02_scroll_function_01.py
    
    from selenium import webdriver
    import time
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("https://www.youtube.com/")
    
    def scroll():
        while True:
            before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
            time.sleep(2)
            after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            time.sleep(2)
            if before_scroll_height == after_scroll_height:
                break
        time.sleep(2)
    
    scroll()
    titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
    print("영상 갯수: ", len(titles))
    for title in titles:
        print(title.text)
  2. 스크롤 후 제목 list 반환하는 내용을 함수로 정의
    ex02_scroll_function_02.py
    
    from selenium import webdriver
    import time
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("https://www.youtube.com/")
    
    def scroll():
        while True:
            before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
            time.sleep(2)
            after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            time.sleep(2)
            if before_scroll_height == after_scroll_height:
                break
        time.sleep(2)
        titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
        print("영상 갯수: ", len(titles))
        return titles
    
    titles = scroll()
    
    for title in titles:
        print(title.text)


ch19 유튜브 크롤링-검색 필터링

💡 이번 차시의 학습목표

✔ 인기급상승 동영상 제목 크롤링

✔ 검색어 입력 후 필터 적용하여 제목 크롤링

01. 유튜브 인기급상승 페이지 영상 제목 크롤링

  1. 접속 주소: 🌐 https://www.youtube.com/feed/trending
  2. 이전 차시에서 진행한 코드에서 주소만 적용하여 진행 가능
    ex01_trending.py
    
    from selenium import webdriver
    import time
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("https://www.youtube.com/feed/trending")
    
    def scroll():
        while True:
            before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
            time.sleep(2)
            after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
            time.sleep(2)
            if before_scroll_height == after_scroll_height:
                break
        time.sleep(2)
        titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
        print("영상 갯수: ", len(titles))
        return titles
    
    titles = scroll()
    
    for title in titles:
        print(title.text)

 

02. 유튜브 검색 결과 조회수순 필터링을 위한 요소 확인하기

  1. 유튜브 검색화면 살펴보기
    1. 검색 결과 화면에서 아래 그림과 같이 ‘필터’를 클릭하면 업로드 날짜, 구분, 길이, 정렬기준 등을 선택할 수 있는 메뉴가 노출됨
    2. 정렬기준의 조회수를 클릭하면 검색 결과가 조회수가 높은순으로 영상목록 정렬됨
  2. 앞서 진행한 방법을 selenium으로 구현하기 위해 필터, 조회수 클릭 요소 살펴보기
    1. 필터 버튼 요소 확인하기
      1. ‘**개발자도구’**를 열고 필터 버튼의 요소 확인
      2. 복사한 요소
        <ytd-toggle-button-renderer align-by-text="" class="style-scope ytd-search-sub-menu-renderer" button-renderer="true"><yt-button-shape><button class="yt-spec-button-shape-next yt-spec-button-shape-next--text yt-spec-button-shape-next--mono yt-spec-button-shape-next--size-m yt-spec-button-shape-next--icon-leading yt-spec-button-shape-next--align-by-text " aria-pressed="false" aria-label="검색 필터" style=""><div class="yt-spec-button-shape-next__icon" aria-hidden="true"><yt-icon style="width: 24px; height: 24px;"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon"><path d="M15,17h6v1h-6V17z M11,17H3v1h8v2h1v-2v-1v-2h-1V17z M14,8h1V6V5V3h-1v2H3v1h11V8z M18,5v1h3V5H18z M6,14h1v-2v-1V9H6v2H3v1 h3V14z M10,12h11v-1H10V12z" class="style-scope yt-icon"></path></g></svg><!--css-build:shady--></yt-icon></div><div class="cbox yt-spec-button-shape-next--button-text-content"><span class="yt-core-attributed-string yt-core-attributed-string--white-space-no-wrap" role="text">필터</span></div><yt-touch-feedback-shape style="border-radius: inherit;"><div class="yt-spec-touch-feedback-shape yt-spec-touch-feedback-shape--touch-response" aria-hidden="true"><div class="yt-spec-touch-feedback-shape__stroke" style=""></div><div class="yt-spec-touch-feedback-shape__fill" style=""></div></div></yt-touch-feedback-shape></button></yt-button-shape>
        <tp-yt-paper-tooltip fit-to-visible-bounds="" offset="8" role="tooltip" tabindex="-1" style="inset: 60px auto auto 7px;"><!--css-build:shady--><div id="tooltip" class="style-scope tp-yt-paper-tooltip hidden" style-target="tooltip">
          검색 필터 열기
        </div>
        </tp-yt-paper-tooltip>
        </ytd-toggle-button-renderer>​​
    2. 필터에서 조회수 요소 확인하기
      1. 개발자도구에서 확인
      2. 복사한 요소
        <a id="endpoint" class="yt-simple-endpoint style-scope ytd-search-filter-renderer" href="/results?search_query=%EB%89%B4%EC%A7%84%EC%8A%A4&amp;sp=CAM%253D">
        <div id="label" class="style-scope ytd-search-filter-renderer" title="조회수순 정렬">
            <yt-formatted-string class="style-scope ytd-search-filter-renderer">조회수</yt-formatted-string>
            <yt-icon id="dismiss-x" icon="yt-icons:dismissal" class="style-scope ytd-search-filter-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon"><path d="M12.7,12l6.6,6.6l-0.7,0.7L12,12.7l-6.6,6.6l-0.7-0.7l6.6-6.6L4.6,5.4l0.7-0.7l6.6,6.6l6.6-6.6l0.7,0.7L12.7,12z" class="style-scope yt-icon"></path></g></svg><!--css-build:shady--></yt-icon>
          </div>
        </a>

 

 

 

 

03. selenium으로 검색 결과에서 조회수순 정렬 과정 구현하기

  1. selenium으로 필터 버튼 클릭하기
    1. 필터 버튼의 xpath 복사하여 find_element() 로 접근
    2. 가져온 요소 click() 으로 클릭
      # 영상에서의 코드 
      filter_button = driver.find_element(By.XPATH, '//*[@id="container"]/ytd-toggle-button-renderer')
      
      # 수정된 코드 
      filter_button = driver.find_element(By.XPATH, '//*[@id="filter-button"]')
      
      filter_button.click()
      
  2. selenium으로 조회수 클릭하기
    1. 조회수의 full xpath 복사하여 find_element() 로 접근
      1. 관련성, 업로드날짜, 조회수, 평점이 모두 같은 xpath, css_selector값을 갖고 있어 구분이 제대로 되지 않아 full xpath 복사하여 사용
    2. 가져온 요소 click() 으로 클릭
      # 영상에서의 코드 
      hits_button = driver.find_element(By.XPATH, '/html/body/ytd-app/div[1]/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[1]/div[2]/ytd-search-sub-menu-renderer/div[1]/iron-collapse/div/ytd-search-filter-group-renderer[5]/ytd-search-filter-renderer[3]/a')
      
      # 수정된 코드
      hits_button = driver.find_element(By.XPATH, '/html/body/ytd-app/ytd-popup-container/tp-yt-paper-dialog/ytd-search-filter-options-dialog-renderer/div[2]/ytd-search-filter-group-renderer[5]/ytd-search-filter-renderer[3]/a')
      
      hits_button.click()
      

04. 정렬된 결과에서 무한 스크롤 수행 후 영상 제목 크롤링 수행

05. 실습 예제

<aside> 📌 실습코드는 코드박스에서 확인해주세요!

</aside>

📥실습 코드

ex02_search_filter.py

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

def scroll():
    while True:
        before_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
        driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight)")
        time.sleep(2)
        after_scroll_height = driver.execute_script("return document.documentElement.scrollHeight")
        time.sleep(2)
        if before_scroll_height == after_scroll_height:
            break
    time.sleep(2)
    titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
    print("영상 갯수: ", len(titles))
    return titles

# 브라우저 실행
driver = webdriver.Chrome()
driver.get("<https://www.youtube.com/>")
search_input = driver.find_element(By.CSS_SELECTOR, "input#search")
search_input.send_keys("뉴진스")
# 검색버튼 클릭
search_button = driver.find_element(By.CSS_SELECTOR, "button#search-icon-legacy")
search_button.click()
time.sleep(2)
# 필터버튼 클릭
filter_button = driver.find_element(By.XPATH, '//*[@id="container"]/ytd-toggle-button-renderer')
filter_button.click()
time.sleep(2)
# 조회수 클릭
hits_button = driver.find_element(By.XPATH, '/html/body/ytd-app/div[1]/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[1]/div[2]/ytd-search-sub-menu-renderer/div[1]/iron-collapse/div/ytd-search-filter-group-renderer[5]/ytd-search-filter-renderer[3]/a')
hits_button.click()
time.sleep(2)
# 무한 스크롤 함수 호출
titles = scroll()

for title in titles:
    print(title.text)

 

 

ch20 유튜브 크롤링-검색 및 스크롤 적용

💡 이번 차시의 학습목표

✔ 인기급상승 동영상을 크롤링하여 제목, 조회수 출력하기

✔ 제목, 조회수 따로 리스트에 저장하기

01. 조회수 값 가져오기

  1. 조회수 표현 요소 확인
    1. 아래 그림과 같이 영상 제목 요소의 a태그 aria-label 속성에서 조회수 값을 확인할 수 있음
    2. aria-label 속성 값
    3. 다나카 초대석 게시자: 침착맨 1일 전 50분 조회수 939,511회
    4. 조회수 값만 표현하는 부분이 없기 때문에 위의 텍스트에서 조회수 숫자만 따로 가져와야 함
  2. 조회수 값을 가져오기 위한 과정</aside>
    1. rfind() method 활용
      1. 해당 변수의 마지막에서 찾기 시작하여 매개변수로 지정한 값이 시작되는 인덱스 값을 반환해줌
        1. find() method는 앞에서부터 찾기 때문에 제목에 ‘조회수’라는 글자가 포함된 경우라면 다른 결과가 나올 수 있음
      2. 조회수 텍스트가 있는 인덱스 찾기
        hits_text.rfind("조회수")
    2. 조회수 값 시작 인덱스 찾기
      1. 조회수로 부터 4번째 인덱스 부터 조회수 값이 작성되어 있음.
        hits_text.find("조회수")+4
    3. 조회수 값 마지막 인덱스 찾기
      1. ‘회’라는 글자 앞까지가 조회수값이 끝나는 인덱스
        hits_text.find("회")
    4. 시작인덱스, 끝 인덱스 값을 활용하여 조회수 숫자만 가져오기
      start_index = hits_text.rfind("조회수")+4
      end_index = hits_text.rfind("회")
      print(hits_text[start_index:end_index])
    5. 구분자 쉼표 제거 후 정수로 변환
      1. 조회수순 정렬 등을 위해선 정수형태의 자료형으로 변환 필요
        hits = hits_text[start_index:end_index]
        hits = int(hits.replace(",", ""))

02. 크롤링 코드에 적용하기

 

  1. 제목, 조회수를 담을 리스트 각각 선언
    hits_list = []
    title_list = []
  2. aria-label 속성값 가져오기
    hits_text = element.get_attribute("aria-label")
  3. 인기급상승 Shorts 의 경우 구조가 달라서 제외
    1. 제외하기 위해 조건문 활용
      if element.get_attribute("aria-label"):
  4. 조회수 값을 가져오기 위한 코드
    1. 조회수 값을 추출한 뒤 제목, 조회수 값을 각각 리스트에 저장
      hits_text = element.get_attribute("aria-label")
      start_index = hits_text.rfind("조회수")+4
      end_index = hits_text.rfind("회")
      hits = hits_text[start_index:end_index]
      hits = int(hits.replace(",", ""))
      title_list.append(element.text)
      hits_list.append(hits)
  5. 완료 후 출력하여 확인
    1. 두 개 리스트를 동시에 반복문으로 사용하기 위해 zip() 활용
      for title, hits in zip(title_list, hits_list):
          print(title, hits)

 

 

 

'Python' 카테고리의 다른 글

[Python] konlpy 형태소 분석  (0) 2024.03.22
[Python] 판다스 Pandas  (1) 2024.03.21
[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] Selenium 소개 및 사용법  (0) 2024.03.18
[Python] 패키지 설치 및 numpy, matplotlib 기초  (0) 2024.03.15

ch14 크롤링 시작하기

💡 이번 차시의 학습목표

✔ 크롤링 실습하기

  • 다나와 - 상품목록 크롤링하기
  • 네이버웹툰 - 웹툰 제목 크롤링하기

01. 다나와 상품 목록 크롤링하기

  1. 검색주소값 가져오기
    1. 다나와 홈페이지 접속
      1. https://www.danawa.com/
    2. 검색창에 노트북 입력 후 검색버튼 클릭
    3. 검색 링크
      1. https://prod.danawa.com/list/?cate=112758&shortcutKeyword=노트북
  2. 상품명 요소 확인하기
    1. 검색 결과에서 상단에는 광고상품이 노출되는데 광고상품은 제외함
    2. 개발자도구 열고 노트북 이름을 표시하는 요소 확인

      <a href="https://prod.danawa.com/info/?pcode=17980199&amp;cate=112758" 
      		target="_blank" onmousedown="_trkEventLog('15상품리스트_상품명')" 
      		name="productName">에이서 니트로 5 AN515-58-94SX</a>​
  3. selenium으로 요소 접근하기
    1. 상품명은 a 태그의 text 속성 형태로 표현되어 있음.
    2. 해당 태그에는 class, id와 같은 속성은 없으며, name=productName 속성 있음.
    3. name 속성을 활용하여 접근
    4. name속성은 By.CSS_SELECTOR 이용
      1. 사용문법
        1. find_elements(By.CSS_SELECTOR, ‘[name=”productName”]’)
        2. 내용이 여러 개이므로 find_elements 사용
        3. [ ]부분을 감싸는 ‘(single quote), name값을 감싸는 “(double quote) 주의하여 작성
  4. 크롤링 데이터 확인하기
    1. 상품명 출력을 위해 for 문 활용

 

 

01-1. 실습 예제

📥실습 코드

ex01_crawling.py

from selenium import webdriver
from selenium.webdriver.common.by import By

# 다나와 상품목록 크롤링
# 브라우저 실행
driver = webdriver.Chrome()
# 접속
driver.get("<https://prod.danawa.com/list/?cate=112758&shortcutKeyword=%EB%85%B8%ED%8A%B8%EB%B6%81>")
notebook_names = driver.find_elements(By.CSS_SELECTOR, '[name="productName"]')
# print(notebook_names)
for name in notebook_names:
    # 코드값이 보임 
    # print(name)
    # 텍스트 출력하기
    print(name.text)

02. 네이버웹툰 웹툰 제목 크롤링하기

  1. 검색주소값 가져오기
    1. 네이버웹툰 홈페이지 접속
      1. https://comic.naver.com/webtoon/weekday
  2. 웹툰제목 요소 확인하기
    1. 전체 웹툰이 보이는 화면에서 월요웹툰 중 첫번째 웹툰의 제목 요소 확인
    2. 개발자도구 열고 웹툰제목을 표시하는 요소 확인
    📥실습 코드
    <a class="ContentTitle__title_area--x24vt" href="/webtoon/list?titleId=648419">
    <span class="ContentTitle__title--e3qXt">뷰티풀 군바리</span></a>​

    selenium으로 요소 접근하기
    1. 웹툰 제목은 a 태그에 표현되어 있고, class=”ContentTitle__title_area--x24vt” 속성을 가지고 있음.
    2. class=”ContentTitle__title_area--x24vt”로 속성 접근
    3. class속성은 By.CLASS_NAME 이용
      1. 사용문법
        1. find_elements(By.CLASS_NAME, ‘ContentTitle__title_area--x24vt’)
        2. 내용이 여러 개이므로 find_elements 사용
  3. 크롤링 데이터 확인하기
    1. 웹툰제목 출력을 위해 for 문 활용(웹툰 갯수가 578개로 출력에 1분이상 소요)

 

 

02-1. 실습 예제

📥실습 코드

ex02_crawling.py

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get("<https://comic.naver.com/webtoon>")
time.sleep(2)
webtoon_titles = driver.find_elements(By.CLASS_NAME, 'ContentTitle__title_area--x24vt')
time.sleep(5)
for name in webtoon_titles:
    print(name.text)
print(len(webtoon_titles))

 

ch15 유튜브 크롤링-시작

💡 이번 차시의 학습목표

✔ 유튜브 홈페이지 구성요소 확인

✔ 유튜브 영상 제목 크롤링 하기

01. 유튜브 홈페이지 구조 살펴보기

  1. **홈페이지 주소: https://www.youtube.com/ 
  2. 크롬 개발자 도구 열어서 영상의 요소 확인
    1. 요소 선택을 위한 아이콘 클릭
    2. 유튜브 영상의 제목 부분 클릭하여 요소 확인
    3. 선택된 부분 마우스 우클릭하여 요소 복사 가능
      1. 예시에서 복사한 요소
        <yt-formatted-string id="video-title" class="style-scope ytd-rich-grid-media" aria-label="54톤 거대 고래 뱃속에서 발견된 것은? [국경없는 영상] 게시자:  YTN 2일 전 1분 54초 조회수 1,400,217회">54톤 거대 고래 뱃속에서 발견된 것은? [국경없는 영상]</yt-formatted-string>​

02. 제목 텍스트 표현 요소 접근하기

  1. 제목 텍스트 위치 확인
    1. 영상의 제목은 <yt-formatted-string></yt-formatted-string> 태그 내에 작성되어 있음
      1. yt- 또는 ytd- 로 시작하는 태그는 사용자 정의 요소(Custom Element)이며, selenium으로 요소를 가져올 때는 id, class 등 html 요소를 주로 이용
        1. 사용자 정의 요소: 표준 html 요소가 아니며, 특정 디자인이나 기능 등을 반복적으로 사용할 때 활용할 수 있음
  2. 제목 텍스트를 가져오기 위해 id=”video-title” 속성 활용
    1. selenium의 find_elements() method를 사용하여 전체 내용을 가져옴
      titles = driver.find_elements(By.ID, "video-title")


    2. XPATH로도 접근 가능
      1. “ ”, ‘ ’ 사용 위치 주의
      titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
  3. titles의 자료형 확인
    1. type 함수 사용하여 가져온 요소의 자료형 확인
      print(type(titles))
    2. list이기 때문에 내용을 확인하기 위해선 반복문을 활용해야 함

 

 

03. 제목 텍스트 출력하기

  1. list를 접근하기 위해 for문 활용하여 출력
    1. text 속성을 사용하여 제목값을 출력할 수 있음
      for title in titles:
      	print(title.text)
    2. 태그 이름 출력
      	print(title.tag_name)
    3. aria-label 속성값 출력
      	print(title.get_attribute("aria-label")

 

 

 

04. 실습 예제

📥실습 코드

ex01_youtube.py

from selenium import webdriver
from selenium.webdriver.common.by import By

# 브라우저 실행
driver = webdriver.Chrome()
driver.get("<https://www.youtube.com/>")
# titles = driver.find_elements(By.ID, "video-title")
titles = driver.find_elements(By.XPATH, '//*[@id="video-title"]')
print(titles)
print(type(titles))
for title in titles:
    print(title.tag_name) # 태그 이름 가져오기
    print(title.text) # inner HTML 값 가져오기
    print(title.get_attribute("aria-label")) # 속성값 가져오기

 

 

ch16 유튜브 크롤링-검색 기능 활용

💡 이번 차시의 학습목표

✔ 검색어를 입력하여 검색된 영상의 제목 크롤링 하기

✔ selenium으로 검색창, 검색버튼 사용하기

01. 유튜브 검색 환경 살펴보기

  1. 유튜브 검색창에 ‘뉴진스’ 입력 후 검색
  2. 검색과정
    1.검색창에 검색어(키워드) 입력 → 🔍검색 버튼 또는 엔터 입력
 
 

02. 검색하는 과정 selenium으로 구현해보기

  1. 과정
    1. selenium으로 유튜브 홈페이지 접속
    2. 검색창 요소 접근
    3. 검색어 입력하기
    4. 검색 버튼 클릭하기 또는 엔터키 입력
    1. selenium으로 유튜브 홈페이지 접속
      driver.get("https://www.youtube.com/")​
    2. 검색어 입력 요소 접근
      1. 검색어 입력창 요소 확인
        1. 개발자 도구 열어서 검색어 입력창 클릭
        2. input 태그이며, id=”search” 속성이 적용되어 있음
          <input id="search" autocapitalize="none" autocomplete="off" autocorrect="off" name="search_query" tabindex="0" type="text" spellcheck="false" placeholder="검색" aria-label="검색" role="combobox" aria-haspopup="false" aria-autocomplete="list" class="gsfi ytd-searchbox" dir="ltr" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; outline: none;">
      2. selenium으로 검색어 입력창 가져오기
        1. css 선택자로 접근(id=”search” 가 적용된 input 태그)
          search_input = driver.find_element(By.CSS_SELECTOR, "input#search")
    3. 검색어 입력하기
      1. selenium의 send_keys() method를 이용하여 검색어 입력
        search_input.send_keys("뉴진스")
    4. 검색버튼 클릭하기
      1. 검색버튼 요소 확인
        • 개발자도구에서 검색 버튼 요소 확인
          <button id="search-icon-legacy" class="style-scope ytd-searchbox" aria-label="검색">
            <yt-icon class="style-scope ytd-searchbox"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon"><path d="M20.87,20.17l-5.59-5.59C16.35,13.35,17,11.75,17,10c0-3.87-3.13-7-7-7s-7,3.13-7,7s3.13,7,7,7c1.75,0,3.35-0.65,4.58-1.71 l5.59,5.59L20.87,20.17z M10,16c-3.31,0-6-2.69-6-6s2.69-6,6-6s6,2.69,6,6S13.31,16,10,16z" class="style-scope yt-icon"></path></g></svg><!--css-build:shady--></yt-icon>
            <tp-yt-paper-tooltip prefix="" class="style-scope ytd-searchbox" role="tooltip" tabindex="-1" style="left: 815.5px; top: 62px;"><!--css-build:shady--><div id="tooltip" class="style-scope tp-yt-paper-tooltip hidden" style-target="tooltip">
            검색
          </div>
          </tp-yt-paper-tooltip>
          </button>
      2. selenium으로 검색 버튼 접근
        • css 선택자로 접근
          search_button = driver.find_element(By.CSS_SELECTOR, "button#search-icon-legacy")
      3. 검색 버튼 클릭하기
        search_button.click()
    5. 검색어 입력 후 엔터 입력으로 검색하기
      1. 검색어 입력까지의 과정은 동일
      2. 검색어 입력 후 엔터키 입력 동작을 위해 Keys 라이브러리 추가
        from selenium.webdriver.common.keys import Keys
      3. 검색어 입력 및 엔터 입력
        search_input.send_keys("뉴진스")
        search_input.send_keys(Keys.RETURN)​

        ex01_search.py
        
        from selenium import webdriver
        from selenium.webdriver.common.by import By
        from selenium.webdriver.common.keys import Keys
        import time
        
        # 브라우저 실행
        driver = webdriver.Chrome()
        driver.get("https://www.youtube.com/")
        search_input = driver.find_element(By.CSS_SELECTOR, "input#search")
        # print(search_input.tag_name)
        search_input.send_keys("뉴진스")
        # 검색버튼 클릭
        search_button = driver.find_element(By.CSS_SELECTOR, "button#search-icon-legacy")
        search_button.click()
        time.sleep(2)
        # 엔터키 입력
        # search_input.send_keys(Keys.RETURN)
        titles = driver.find_elements(By.ID, "video-title")
        for title in titles:
            print(title.text)

03. 다른 방법으로 검색 결과 가져오기

  1. 유튜브 검색 시 브라우저의 주소값 살펴보기
    1. ‘뉴진스’ 검색하는 경우 주소값
      1. https://www.youtube.com/results?search_query=뉴진스
    2. ‘bts’ 검색하는 경우 주소값
      1. https://www.youtube.com/results?search_query=bts
  2. 주소값 분석
    1. https://www.youtube.com/results?search_query=’ 부분은 동일하며 search_query=’검색어’ 형태로 검색어에 따라 마지막 부분만 바뀜
  3. selenium으로 주소값에 검색어를 포함하여 시작
    1. ‘뉴진스’ 검색결과 페이지로 직접 접속
      driver.get("https://www.youtube.com/results?search_query=뉴진스")
    2. 실습코드
      ex02_search.py
      
      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from selenium.webdriver.common.keys import Keys
      import time
      
      driver = webdriver.Chrome()
      driver.get("<https://www.youtube.com/results?search_query=뉴진스>")
      
      titles = driver.find_elements(By.ID, "video-title")
      for title in titles:
          print(title.text)
      ​
  4. 검색어를 콘솔로 입력받아 적용하기
    1. input 함수로 입력값 변수로 가져오기(아래 문장이 가장 먼저 실행되어야 함)
      q = input("검색어를 입력하세요: ")

      검색어를 요청 주소에 추가하기
      1. ‘+’ 를 이용하여 연결
        driver.get("<https://www.youtube.com/results?search_query=>"+q)
    2. 실습코드
      ex03_search.py
      
      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from selenium.webdriver.common.keys import Keys
      import time
      
      q = input("검색어를 입력하세요: ")
      driver = webdriver.Chrome()
      driver.get("<https://www.youtube.com/results?search_query=>"+q)
      
      titles = driver.find_elements(By.ID, "video-title")
      for title in titles:
          print(title.text)
      ​

 

 

'Python' 카테고리의 다른 글

[Python] 판다스 Pandas  (1) 2024.03.21
[Python] 유튜브 크롤링(2)  (0) 2024.03.20
[Python] Selenium 소개 및 사용법  (0) 2024.03.18
[Python] 패키지 설치 및 numpy, matplotlib 기초  (0) 2024.03.15
[Python] 함수와 모듈  (0) 2024.03.11

ch11 Selenium 소개 및 시작

💡 이번 차시의 학습목표

✔ 크롤링 개념

✔ Selenium 소개 및 사용방법

✔ Selenium 시작하기

01. 크롤링이란

  1. 웹 크롤러가 하는 작업
  2. 웹 크롤러란?
    1. 조직적, 자동화된 방법으로 월드 와이드 웹을 탐색하는 컴퓨터 프로그램 (위키백과)
  3. 특정 웹사이트 또는 여러 웹사이트의 정보를 수집하는데 사용됨.
  4. 일종의 스크랩

02. 크롤링의 종류 및 특징

  1. 정적 크롤링
    1. 브라우저를 통해 특정 페이지에 접속한 이후 보이는 내용만 크롤링
    2. 한 페이지에 열린 내용만 가져오기 때문에 속도가 빠름
    3. BeautifulSoup
  2. 동적 크롤링
    1. 입력, 클릭, 스크롤 등 움직임을 통해 웹페이지를 이용하면서 바뀌는 내용을 지속적으로 크롤링
    2. 다양한 데이터를 가져올 수 있지만 상대적으로 속도가 느림
    3. Selenium
  3. 동적 크롤링 vs 정적 크롤링 비교

정적크롤링 동적크롤링

접근성 정해진 주소를 통해 일회성 접근 브라우저를 사용하여 주소 또는 페이지 이동 가능
크롤링 범위 열려있는 내용만 수집 가능 클릭, 텍스트 입력 등 동적인 활동이 가능하기 때문에 범위에 한계는 없음
속도 빠름 느림

03. Selenium 이란

  1. 웹 브라우저를 자동화하여 사용하기 위한 툴
  2. 특정 웹 주소에 접속하고 클릭, 텍스트입력, 스크롤 등 사용자가 브라우저에서 사용할 수 있는 대부분의 동작을 프로그래밍으로 지원
  3. 무료로 사용가능한 라이브러리
  4. 지원언어
    1. Python, Java, C#, Javascript, Kotlin 등 다양한 언어 지원
  5. 공식 홈페이지
  6. 🌐 https://www.selenium.dev/
  7. Selenium 시작하기
    1. 시작하기 전에 파이썬(3.8.10), 크롬브라우저, Visual Studio Code는 반드시 설치되어 있어야 합니다.
    2. selenium 모듈 설치 (필수)
      1. 터미널에서 pip 를 이용하여 selenium 설치
      2. pip install selenium
    3. 브라우저 제어를 위한 webdriver 사용
      1. from selenium import webdriver

04. 실습 예제

  1. selenium으로 구글 홈페이지 접속해보기
ex01_selenium.py

# 브라우저(크롬) 실행
driver = webdriver.Chrome()
# 주소 입력(구글 홈페이지)
driver.get("https://www.google.com")

 

 

ch12 Selenium 기본 사용법 - find_element

💡 이번 차시의 학습목표

✔ Selenium으로 웹페이지의 요소 가져오기

✔ find_element(), find_elements() 사용하기

01. selenium으로 웹페이지의 요소를 가져오기

✅selenium은 html의 다양한 요소에 접근할 수 있는 method를 제공함

✅해당 페이지의 id, class, 태그, css 선택자 등 거의 모든 요소에 접근 가능

✅요소에 접근하여 해당 요소의 속성, text 값 등을 가져올 수 있음

02. 요소에 접근할 때 사용하는 주요 method

  1. find_element()
    1. 해당 요소(id, class, tag 등) 하나를 가져옴
    2. 똑같은 요소가 여러 개라면 첫 번째 요소만 가져옴
  2. find_elements()
    1. 똑같은 요소가 여러 개일 때 해당 요소를 모두 가져옴
    2. python list 타입으로 가져올 수 있음

03. find_element() method

  1. from selenium.webdriver.common.by import By 를 작성해야함
  2. 태그 요소 가져오기
    1. find_element(By.TAG_NAME, ‘태그이름’)
    2. ex) div 태그 가져오기
      1. find_element(By.TAG_NAME, ‘div’)
  3. id 요소 가져오기
    1. find_element(By.ID, ‘id name’)
    2. ex) id가 main 인 요소 가져오기
      1. find_element(By.ID, ‘main’)
  4. class 요소 가져오기
    1. find_element(By.CLASS_NAME, ‘class name’)
    2. class는 여러 개의 태그에 적용되는 경우가 대부분이기 때문에 특정 class요소를 가져오는 경우에는 find_elements 쓰는 것을 권장
    3. ex) class가 btn 인 요소 가져오기
      1. find_element(By.CLASS_NAME, ‘btn’)
  5. css selector로 요소 가져오기
    1. find_element(By.CSS_SELECTOR, ‘선택자 문법’)
    2. ex) input 태그의 name이 username인 요소 가져오기
      1. find_element(By.CSS_SELECTOR, ‘[name=”username”]’)

03. find_elements() method

  1. 사용법은 find_element와 동일함
  2. list 타입으로 값을 리턴하기 때문에 반복문으로 접근하여 사용

04. 실습 예제 - 많이 활용되는 라이브러리 연습하기

📥실습 코드

  1. 태그 요소 가져오기
    ex01_tag_01.py
    
    driver = webdriver.Chrome()
    driver.get("https://www.example.com")
    # p 태그 요소 가져오기
    p_element = driver.find_element(By.TAG_NAME, 'p')
    print(p_element)
    # 텍스트만 출력
    print(p_element.text)
  2. p태그 요소 모두 가져와서 출력하기
    ex01_tag_02.py
    
    # p 태그 요소 모두 가져오기 
    p_elements = driver.find_elements(By.TAG_NAME, 'p')
    print(p_elements)
    
    # p_elements의 타입 확인
    print(type(p_elements))
    for p in p_elements:
        print(p)
        print(p.text)

  3. id 요소 접근하기
    ex02_id.py
    
    driver = webdriver.Chrome()
    driver.get("https://www.python.org/")
    id_element = driver.find_element(By.ID, 'site-map')
    print(id_element)
    print(id_element.text)

  4. class 요소 접근하기
    ex03_class.py
    
    driver.get("https://www.python.org/")
    class_element = driver.find_elements(By.CLASS_NAME, 'main-content')
    for c in class_element:
        print(c.text)

 

ch13 Selenium 기본 사용법 - 요소 접근하기

💡 이번 차시의 학습목표

✔ xpath로 요소 접근하기

✔ selenium으로 키입력, 클릭 등 동적 제어하기

 

01. xpath

  1. W3C 표준으로 문서의 구조를 통해 경로 위에 지정한 구문을 사용하여 항목을 배치하고 처리하는 방법을 기술하는 언어(위키백과)
    1. W3C(World Wide Web Consortium): 웹 표준, 웹 가이드라인 등을 개발하는 국제 컨소시엄
  2. xml 문장 속의 요소, 속성 등을 지정하기 위한 언어
  3. html도 xml의 일종이기 때문에 xpath로 해당 요소에 접근하는 것이 가능함
  4. 브라우저의 개발자 도구에서도 xpath를 복사하는 기능 제공

02. example.com에서 xpath 확인해보기

  1. 브라우저에서 🌐example.com 접속
  2. F12눌러서 개발자도구 열기
    1. 또는 아래 그림처럼 메뉴에서 접근 가능
  3. h1태그 요소 접근하여 xpath 복사하기
      1. 해당요소에서 우클릭 후 Copy → Copy Xpath 클릭하면 해당 요소의 xpath를 복사할 수 있음
      2. 복사한 xpath: /html/body/div/h1

03. selenium 동작 제어 method

  1. find_element로 가져온 요소 클릭하기
  2. ✅ driver.find_element(By.XPATH, ‘xpath값’).click()
  3. find_element로 가져온 요소에 값 작성하기✅ driver.find_element(By.XPATH, ‘xpath값’).send_keys(”입력값”)
  4. ✅ input 요소에 접근을 한 뒤 send_keys() 로 입력할 값 전달

04. 실습 예제

  1. 네이버 홈페이지에 접속하여 로그인 버튼 클릭
    1. 🔍네이버 홈페이지 접속
      driver.get("<https://www.naver.com>")​
    2. 로그인버튼 요소 가져오기
      1. 개발자도구로 로그인 버튼 요소 확인 후 xpath 복사
        # 영상에서의 코드 
        login_button = driver.find_element(By.XPATH, '//*[@id="account"]/a')
        
        # 수정된 코드 
        login_button = driver.find_element(By.XPATH, '//*[@id="account"]/div/a')
        
    3. 로그인버튼 클릭
      login_button.click()
  2. 네이버 검색창에 파이썬 이라 입력하고 검색버튼 클릭
    1. 🔍네이버 홈페이지 접속
      driver.get("<https://www.naver.com>")​​
    2. 검색창 요소 가져오기
      1. 개발자도구로 검색창 요소 확인 후 xpath 복사
        search = driver.find_element(By.XPATH, '//*[@id="query"]')
    3. 검색어 입력
      search.send_keys("파이썬")
    4. 검색버튼 요소 가져오기
      # 영상에서의 코드 
      search_button = driver.find_element(By.XPATH, '//*[@id="search_btn"]')
      
      # 수정된 코드 
      search_button = driver.find_element(By.XPATH, '//*[@id="search-btn"]')
      
    5. 검색버튼 클릭
      search_button.click()

 

'Python' 카테고리의 다른 글

[Python] 유튜브 크롤링(2)  (0) 2024.03.20
[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] 패키지 설치 및 numpy, matplotlib 기초  (0) 2024.03.15
[Python] 함수와 모듈  (0) 2024.03.11
[Python] 조건문과 반복문  (0) 2024.03.08

ch08 파이썬 패키지 설치 및 numpy, matplotlib 기초

 💡 이번 차시의 학습목표

✔ 파이썬 패키지 설치

✔ numpy, matplotlib 기본 사용

 

01. pip

  1. package installer for Python
  2. 파이썬 패키지를 설치하고 관리하는 패키지 매니저
  3. 프로그램을 설치할 수 있도록 도와주는 도구
  4. pip는 파이썬을 설치하면 기본적으로 포함되어 있음.
  5. cmd 에서 pip 입력 후 확인

02. 패키지 설치 방법

  1. 터미널에서 아래와 같은 명령어 입력 후 실행
    >> pip install [패키지 이름]​
  2. 설치된 패키지 리스트 확인
    >> pip list​

03. 대표적인 패키지들

  1. numpy
    1. 행렬이나 일반적으로 대규모 다차원 배열을 쉽게 처리할 수 있도록 지원하는 라이브러리
      1. 다차원 배열 자료구조인 ndarray 지원
    2. 수치해석 등 수학 및 과학 연산을 위해 효율적으로 구현된 기능 제공
    3. 공식 홈페이지
    4. 🌐 https://numpy.org/
  2. pandas
    1. 데이터 조작 및 분석을 위한 라이브러리
    2. 쉼표로 구분된 값, JSON, Excel과 같은 다양한 파일 형식에서 데이터를 가져올 수 있음
    3. 데이터를 표 형태로 다룰 수 있음
      1. 데이터의 종류
        1. Series(1차원 구조), DataFrame(2차원 구조), Panel(3차원 구조)
        2. Series, DataFrame을 많이 사용함
    4. 공식 홈페이지
    5. 🌐 https://pandas.pydata.org/
  3. matplotlib
    1. 데이터를 시각화(그래프, 도표 등)하기 위한 라이브러리
    2. 2차원 그래프, 막대그래프, 히스토그램 등 다양한 차트 지원
    3. 공식 홈페이지
    4. 🌐 https://matplotlib.org/
  4. scikit-learn(사이킷런)
    1. 머신러닝을 위한 라이브러리
    2. 학습/검증/예측 데이터로 데이터를 분리할 수 있으며 다양한 머신러닝 알고리즘을 지원함
    3. 공식 홈페이지
    4. 🌐 https://scikit-learn.org/stable/
  5. django(장고), flask
    1. 웹 개발을 위한 웹 프레임워크 라이브러리
    2. django는 데이터베이스와의 연동을 모두 지원하는 풀스택 프레임워크이며, flask는 데이터베이스 연동을 위해선 별도의 라이브러리를 사용해야하며, 상대적으로 가벼우며, 복잡하지 않은 웹 개발에 활용됨
    3. 공식 홈페이지🌐 flask: https://flask.palletsprojects.com/en/2.2.x/
    4. 🌐 django: https://www.djangoproject.com/
  6. beautiful soup, selenium
    1. html, xml 문서를 추출하고 구조적인 분석을 도와주는 라이브러리로 웹 크롤링에 많이 활용됨
    2. beautiful soup은 정적인 페이지, selenium은 마우스 동작, 키보드 동작 등의 기능도 프로그래밍으로 구현할 수 있도록 지원하여 보다 동적인 페이지 접근이 가능함
    3. 공식 홈페이지🌐 selenium: https://www.selenium.dev/
    4. 🌐 beautiful soup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

04. 실습 예제

 📌 실습코드는 코드박스에서 확인해주세요!

 

📥실습 코드

  1. numpy
    1. 설치 및 사용 방법
      # 설치
      >> pip install numpy
      
      # 사용
      import numpy as np​
    2. 배열 정렬하기
      ex01_numpy_01.py
      
      import numpy as np
      
      # 배열 선언
      arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
      print(arr)
      # 정렬 함수 호출
      arr = np.sort(arr)
      print(arr)
    3. 배열 합치기
      ex01_numpy_02.py
      
      import numpy as np
      
      # 배열 합치기
      a = np.array([1, 2, 3, 4])
      b = np.array([5, 6, 7, 8])
      c = np.concatenate((a, b))
      print(c)
    4. 배열 연산하기
      ex01_numpy_03.py
      
      import numpy as np
      
      # 배열 연산하기
      a = np.array([1, 2, 3, 4])
      print(a)
      b = a + 10
      print(b)
      c = a - b
      print(c)
    5. 배열 슬라이싱(특정 인덱스 범위만 접근)
      ex01_numpy_04.py
      
      import numpy as np
      
      # 배열 슬라이싱
      a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
      print(a[:2]) # 0~1번 인덱스
      print(a[1:2]) # 1~1번 인덱스
      print(a[3:8]) # 3~7번 인덱스
      print(a[6:]) # 6번 인덱스 부터 마지막
  2. matplotlib
    1. 설치 및 사용 방법
      1. pyplot 모듈: 그래프 만들 때 주로 사용하여 import 추가
        ex01_numpy_04.py
        
        import numpy as np
        
        # 배열 슬라이싱
        a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
        print(a[:2]) # 0~1번 인덱스
        print(a[1:2]) # 1~1번 인덱스
        print(a[3:8]) # 3~7번 인덱스
        print(a[6:]) # 6번 인덱스 부터 마지막​
    2. 2차원 그래프 그리기
      1. y축 값만 정의하기
        ex02_matplot_01.py
        
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        
        # plot(): 기본적인 x축, y축으로 구성된 2차원 그래프를 만들어주는 함수 
        # show(): 정의된 그래프 출력
        
        # y축 값만 정의 
        plt.plot([1, 2, 3, 4])
        plt.show()
      2. x축, y축 값 정의하기, 축 label 표시하기
        ex02_matplot_02.py
        
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        
        # x축, y축 값 함께 정의 
        # plt.plot([1, 2, 3, 4], [2, 5, 6, 10])
        x_values = [1, 2, 3, 4]
        y_values = [2, 5, 6, 10]
        plt.plot(x_values, y_values)
        # 축 label 표시하기 
        plt.xlabel("x axis label")
        plt.ylabel("y axis label")
        plt.show()
      3. 마커 표시하기
        1. 마커 옵션
        2. 🌐 https://matplotlib.org/stable/api/markers_api.html#module-matplotlib.markers
        ex02_matplot_03.py
        
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        
        x_values = [1, 2, 3, 4]
        y_values = [2, 5, 6, 10]
        # marker 표시(동그라미)
        # plt.plot(x_values, y_values, "o")
        # marker 표시(동그라미, 선)
        # plt.plot(x_values, y_values, "o-")
        # marker 표시(네모, 선)
        # plt.plot(x_values, y_values, "s-")
        # marker 표시(동그라미, 대시선)
        # plt.plot(x_values, y_values, "o--")
        plt.xlabel("x axis label")
        plt.ylabel("y axis label")
        plt.show()
        

 

 

 

 

ch09 HTML, CSS, Javascript 소개 및 선택자 활용

💡 이번 차시의 학습목표

✔ HTML, CSS, javascript의 역할 이해

✔ HTML, CSS, javascript 기초문법 다뤄보기

 

01. 웹 화면의 구성

  1. 거의 모든 웹사이트의 화면은 HTML, CSS, javascript로 구성됨
  2. 현재는 HTML5 라는 웹표준을 이용하여 웹페이지를 개발하고 있으며, 크롬, 사파리, 엣지 등 웹 브라우저를 이용하여 웹페이지를 이용할 수 있음
  3. html파일에 HTML, CSS, javascript문법을 활용하여 화면을 구성함
  4. 웹 화면 구성요소
    1. HTML(Hyper Text Markup Language)
      1. 웹페이지 화면의 내용 및 구조를 정의하는 언어이며, 태그를 사용해서 영역을 구분함
      2. 텍스트, 이미지 등을 표현함
    2. CSS(Cascading Style Sheets)
      1. 웹화면 요소에 대한 색상, 글꼴, 크기, 레이아웃 등을 지정할 수 있음
      2. 시각적 표현에 활용
    3. javascript
      1. 정적인 htm에 동적인 기능을 지정할 수 있는 프로그래밍 언어
      2. 요소변경, 시각적인 변경 등 화면에 대한 동작을 지정할 수 있음

02. 기초문법 이해하기

  1. 기본 구조
    1. 가장 기본적인 구조이며, 화면에 표현되는 내용은 body 태그 내에 작성
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <title>Document</title>
      </head>
      <body>
          
      </body>
      </html>​


    2. 화면에 안녕하세요 텍스트 출력하기
      ex01_basic.html
      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <title>Document</title>
      </head>
      <body>
          안녕하세요
      </body>
      </html>​


      실행을 위해 extension에서 live server 검색하여 설치

    3. 태그 적용하여 출력해보기
      <h2>안녕하세요</h2>​


  2. CSS 적용해보기
    1. head 태그 내에 style 태그를 추가하여 화면 요소에 대한 스타일 지정
    2. 지정한 요소에 대해서만 해당 스타일 지정됨
      1. h2태그에 글자색을 빨간색으로 지정
        ex02_css.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title>Document</title>
            <style>
                h2 {
                    color: red;
                }
            </style>
        </head>
        <body>
            <div>
                <p>첫번째 div p 태그</p>
                <h2>첫번째 div h2 태그</h2>
            </div>
            <div>
                <h2>두번째 div h2 태그</h2>
                <h3>두번째 div h3 태그</h3>
            </div>
        </body>
        </html>​
    3. div 태그에 배경색을 노란색으로 지정
      div {
            background-color: yellow;
          }​

  3. javascript 적용해보기
    1. head 태그 내에 script 태그를 추가하여 javascript 코드 작성
    2. 버튼클릭하여 javascript 함수 호출해보기
      1. 버튼 클릭시 함수호출을 위해 onclick 속성 사용
        ex03_javascript.html
        
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title>Document</title>
            <script>
                function fun1() {
        						console.log("콘솔에 출력됩니다");
                    alert("안녕하세요");
                }
            </script>
        </head>
        <body>
            <button onclick="fun1()">버튼</button>
        </body>
        </html>​

03. CSS 선택자(Selector)

  1. HTML 요소를 선택할 수 있으며, CSS 스타일적용, javascript 에서 요소선택 등에 활용할 수 있음
    ex04_selector_01.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        <div id="id1">
            <p class="class1">첫번째 div p 태그</p>
            <h2 class="class1">첫번째 div h2 태그</h2>
        </div>
        <div id="id2">
            <h2 class="class1">두번째 div h2 태그</h2>
            <h3 class="class2">두번째 div h3 태그</h3>
        </div>
    </body>
    </html>​


  2. 주요 선택자 문법
    1. 태그 선택자
      1. 스타일을 적용할 태그 이름을 쓰고 중괄호 안에 css 문법을 작성함
      2. h2 태그 요소에는 글자색 빨간색, div 태그 요소에는 배경색 노란색
        ex04_selector_02.html
        
        h2 {
        	  color: red;
            }
        div {
            background-color: yellow;
            }​


    2. id 선택자
      1. id선택자는 하나의 html 문서에서 중복되는 id요소 값을 가지지 않도록 함
      2. id1 이라는 요소에 글자색을 파란색으로 지정. id3요소는 배경색 초록색
      3. id 선택자 사용할 때는 앞에 #을 붙임
        ex04_selector_03.html
        
        #id1 {
              color: blue;
        	    }
        #id3 {
              background-color: green;
        	    }​


    3. class 선택자
      1. class 선택자는 여러 요소에 적용하는 것이 가능
      2. class1 요소에 글자색을 빨간색으로 지정. class2 요소는 배경색 노란색
        1. 동시에 여러 디자인 적용가
      3. class 선택자 사용할 때는 앞에 .을 붙임
        ex04_selector_04.html
        
        .class1 {
                color: red;
        		    }
        .class2 {
        		    background-color: yellow;
        		    }​



    4. 자손 선택자
      1. 하위 요소를 선택할 때 사용하며 공백을 이용하여 구분함
        ex04_selector_05.html
        
        /* id1이 적용된 요소 내의 h2 태그 요소 */
        #id1 h2 {
        			   color: blue;
        				}
        /* id2가 적용된 요소 내의 class2 클래스가 적용된 요소 */
        #id2 .class2 {
        					    color: red;
        							}​


    5. 결합 선택자
      1. div태그요소 중에서 id1이라는 id가 적용된 요소 선택
        div#id1 {
                color: blue;
                }​

 

ch10 Javascript DOM, BOM API

<aside> 💡 이번 차시의 학습목표

✔ javascript DOM API 활용

✔ javascript로 스크롤 제어

✔브라우저 개발자도구 활용하기

</aside>

01. javascript DOM API 활용하기

  1. DOM(Document Object Model, 문서객체모델)
    1. html 문서의 각 요소를 계층으로 표현하여 생성, 변형, 삭제할 수 있도록 하는 인터페이스
    2. DOM 계층 이미지(출처: 위키백과)
  2. DOM API(Application Programming Interface)
    1. javascript에서 html요소를 제어하기 위해 제공되는 함수
    2. 객체 형태로 접근할 수 있으며, 현재 문서는 document로 접근함
    3. 주요 method
      1. getElementById(”id이름”): 해당 id 이름을 가진 요소를 가져옴
      2. getElementsByClassName(”Class이름”): 해당 class 이름을 가진 요소를 모두 가져옴
      3. getElementsByTagName(”Tag이름”): 해당 tag 요소를 모두 가져옴
    4. 실습
      1. id1 요소 가져와서 콘솔에 출력
      2. ele1 = document.getElementById("id1"); console.log(ele1);
      3. class2 요소 가져와서 콘솔에 출력
        1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
        2. ele1 = document.getElementsByClassName("class2") console.log(ele1); console.log(ele1[0]);
      4. h2 요소 가져와서 콘솔에 출력
        1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
        2. ele1 = document.getElementsByTagName("h2") console.log(ele1); console.log(ele1[0]);

02. javascript 로 스크롤 제어하기

  1. 페이지 높이 확인
    1. scrollHeight 속성으로 현재 페이지의 높이 확인
    2. height = document.documentElement.scrollHeight; console.log(height);
  2. css로 페이지의 높이를 지정한 후 페이지 높이 확인
  3. body { height: 3000px; }
  4. 스크롤을 제일 하단으로 내리기
    1. 브라우저 제어를 위해서 window 객체 활용
      1. BOM(Browser Object Model, 브라우저객체모델)으로 브라우저에 대한 제어를 할 수 있는 API
      2. window 객체로 브라우저의 제일 하단으로 스크롤 내리기
        1. scrollTo() method 활용
          1. 첫번째 매개변수는 가로, 두번째 매개변수는 세로 스크롤값
          height = document.documentElement.scrollHeight;
          console.log(height);
          window.scrollTo(0, document.documentElement.scrollHeight)
          

03. 브라우저 개발자도구 살펴보기

  1. 개발자도구
    1. 현재 웹페이지의 요소, 콘솔, 디자인 요소 확인 등을 할 수 있음
    2. 대부분의 브라우저(크롬, 사파리, 엣지 등)에서 제공
    3. 크롤링하고자 하는 웹사이트의 요소 분석을 위해 개발자도구 사용은 필수
  2. 개발자도구 살펴보기
    1. 크롬 브라우저에서 F12키를 누르면 우측에 개발자도구가 보임
    2. 파이썬 홈페이지 접속 후 개발자도구 확인
    3. 아래 그림과 같이 아이콘 클릭 후 홈페이지의 파이썬 로고 클릭
    4. 아래와 같이 파이썬 로고의 요소를 확인할 수 있음
    5. <img class="python-logo" src="/static/img/python-logo@2x.png" alt="python™" width="218" height="62">

      ch10 Javascript DOM, BOM API

      <aside> 💡 이번 차시의 학습목표✔ javascript로 스크롤 제어</aside>
      1. DOM(Document Object Model, 문서객체모델)
        1. html 문서의 각 요소를 계층으로 표현하여 생성, 변형, 삭제할 수 있도록 하는 인터페이스
        2. DOM 계층 이미지(출처: 위키백과)

      2. DOM API(Application Programming Interface)
        1. javascript에서 html요소를 제어하기 위해 제공되는 함수
        2. 객체 형태로 접근할 수 있으며, 현재 문서는 document로 접근함
        3. 주요 method
          1. getElementById(”id이름”): 해당 id 이름을 가진 요소를 가져옴
          2. getElementsByClassName(”Class이름”): 해당 class 이름을 가진 요소를 모두 가져옴
          3. getElementsByTagName(”Tag이름”): 해당 tag 요소를 모두 가져옴
        4. 실습
          1. id1 요소 가져와서 콘솔에 출력
          2. ele1 = document.getElementById("id1"); console.log(ele1);
          3. class2 요소 가져와서 콘솔에 출력
            1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
            2. ele1 = document.getElementsByClassName("class2") console.log(ele1); console.log(ele1[0]);
          4. h2 요소 가져와서 콘솔에 출력
            1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
            2. ele1 = document.getElementsByTagName("h2") console.log(ele1); console.log(ele1[0]);

      02. javascript 로 스크롤 제어하기

      1. 페이지 높이 확인
        1. scrollHeight 속성으로 현재 페이지의 높이 확인
        2. height = document.documentElement.scrollHeight; console.log(height);
      2. css로 페이지의 높이를 지정한 후 페이지 높이 확인
      3. body { height: 3000px; }
      4. 스크롤을 제일 하단으로 내리기
        1. 브라우저 제어를 위해서 window 객체 활용
          1. BOM(Browser Object Model, 브라우저객체모델)으로 브라우저에 대한 제어를 할 수 있는 API
          2. window 객체로 브라우저의 제일 하단으로 스크롤 내리기
            1. scrollTo() method 활용
              1. 첫번째 매개변수는 가로, 두번째 매개변수는 세로 스크롤값
              height = document.documentElement.scrollHeight;
              console.log(height);
              window.scrollTo(0, document.documentElement.scrollHeight)
              

      03. 브라우저 개발자도구 살펴보기

      1. 개발자도구
        1. 현재 웹페이지의 요소, 콘솔, 디자인 요소 확인 등을 할 수 있음
        2. 대부분의 브라우저(크롬, 사파리, 엣지 등)에서 제공
        3. 크롤링하고자 하는 웹사이트의 요소 분석을 위해 개발자도구 사용은 필수
      2. 개발자도구 살펴보기
        1. 크롬 브라우저에서 F12키를 누르면 우측에 개발자도구가 보임
        2. 파이썬 홈페이지 접속 후 개발자도구 확인
        3. 아래 그림과 같이 아이콘 클릭 후 홈페이지의 파이썬 로고 클릭
        4. 아래와 같이 파이썬 로고의 요소를 확인할 수 있음
        5. <img class="python-logo" src="/static/img/python-logo@2x.png" alt="python™" width="218" height="62">

          ch10 Javascript DOM, BOM API

          <aside> 💡 이번 차시의 학습목표✔ javascript로 스크롤 제어</aside>
          1. DOM(Document Object Model, 문서객체모델)
            1. html 문서의 각 요소를 계층으로 표현하여 생성, 변형, 삭제할 수 있도록 하는 인터페이스
            2. DOM 계층 이미지(출처: 위키백과)
          2. DOM API(Application Programming Interface)
            1. javascript에서 html요소를 제어하기 위해 제공되는 함수
            2. 객체 형태로 접근할 수 있으며, 현재 문서는 document로 접근함
            3. 주요 method
              1. getElementById(”id이름”): 해당 id 이름을 가진 요소를 가져옴
              2. getElementsByClassName(”Class이름”): 해당 class 이름을 가진 요소를 모두 가져옴
              3. getElementsByTagName(”Tag이름”): 해당 tag 요소를 모두 가져옴
            4. 실습
              1. id1 요소 가져와서 콘솔에 출력
                ele1 = document.getElementById("id1");
                console.log(ele1);​​


              2. class2 요소 가져와서 콘솔에 출력
                1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
                  ele1 = document.getElementsByClassName("class2")
                  console.log(ele1);
                  console.log(ele1[0]);​


              3. h2 요소 가져와서 콘솔에 출력
                1. 여러 개 요소를 가져오기 때문에 배열 객체처럼 인덱스로 접근 가능
                  ele1 = document.getElementsByTagName("h2")
                  console.log(ele1);
                  console.log(ele1[0]);​


          02. javascript 로 스크롤 제어하기

          1. 페이지 높이 확인
            1. scrollHeight 속성으로 현재 페이지의 높이 확인
              height = document.documentElement.scrollHeight;
              console.log(height);
          2. css로 페이지의 높이를 지정한 후 페이지 높이 확인
            body {
                  height: 3000px;
                  }​
          3. 스크롤을 제일 하단으로 내리기
            1. 브라우저 제어를 위해서 window 객체 활용
              1. BOM(Browser Object Model, 브라우저객체모델)으로 브라우저에 대한 제어를 할 수 있는 API
              2. window 객체로 브라우저의 제일 하단으로 스크롤 내리기
                1. scrollTo() method 활용
                  1. 첫번째 매개변수는 가로, 두번째 매개변수는 세로 스크롤값
                  height = document.documentElement.scrollHeight;
                  console.log(height);
                  window.scrollTo(0, document.documentElement.scrollHeight)
                  

          03. 브라우저 개발자도구 살펴보기

          1. 개발자도구
            1. 현재 웹페이지의 요소, 콘솔, 디자인 요소 확인 등을 할 수 있음
            2. 대부분의 브라우저(크롬, 사파리, 엣지 등)에서 제공
            3. 크롤링하고자 하는 웹사이트의 요소 분석을 위해 개발자도구 사용은 필수
          2. 개발자도구 살펴보기
            1. 크롬 브라우저에서 F12키를 누르면 우측에 개발자도구가 보임
            2. 파이썬 홈페이지 접속 후 개발자도구 확인
            3. 아래 그림과 같이 아이콘 클릭 후 홈페이지의 파이썬 로고 클릭
            4. 아래와 같이 파이썬 로고의 요소를 확인할 수 있음
              <img class="python-logo" src="/static/img/python-logo@2x.png" alt="python™" width="218" height="62">

 

'Python' 카테고리의 다른 글

[Python] 유튜브 크롤링(1)  (0) 2024.03.19
[Python] Selenium 소개 및 사용법  (0) 2024.03.18
[Python] 함수와 모듈  (0) 2024.03.11
[Python] 조건문과 반복문  (0) 2024.03.08
[Python] 파이썬 기본 문법  (0) 2024.01.30

ch05 파이썬 함수 기초

💡 이번 차시의 학습목표

✔ 함수의 의미, 함수 문법

✔ 함수 연습

✔ 사용자 정의 함수, 내장 함수

 

01. 함수

  1. 특정 기능을 수행하기 위한 코드블록
  2. def 키워드를 이용하여 함수를 정의 → 매개변수, 리턴
  3. 함수 내에 작성한 코드는 항상 실행되는 것이 아니라 호출을 해야 실행
  4. 함수의 기본 구조
    # 매개변수 x, 리턴 x
    def [함수이름]:
    	함수호출시 실행내용
    
    # 매개변수 x, 리턴 o
    def [함수이름]:
    	함수호출시 실행내용
    	return 리턴문장
    
    # 매개변수 o, 리턴 x
    def [함수이름(매개변수)]:
    	함수호출시 매개변수를 활용하는 실행내용
    	
    # 매개변수 o, 리턴 o
    def [함수이름(매개변수)]:
    	함수호출시 매개변수를 활용하는 실행내용
    	return 리턴문장​​
  5. 안녕하세요를 출력해보는 함수
    1. 함수를 호출하면 '안녕하세요'를 함수 내부에서 출력
      ex01_function_basic.py
      
      def hello():
          print("안녕하세요1")
      
      hello()


    2. 함수를 호출하면 '안녕하세요'를 리턴받아 리턴값을 함수 외부에서 출력
      ex02_function_return.py
      
      def hello():
          # return "안녕하세요"
          hello = "안녕하세요"
          return hello
      # print(hello())
      return_var = hello()
      print(return_var)


    3. 함수를 호출하면서 '안녕하세요'를 전달하고 함수 내부에서 출력
      ex03_function_param.py
      
      def hello(h):
          print(h)
      # hello("안녕하세요")
      param_var = "안녕하세요"
      hello(param_var)


    4. 함수를 호출하면서 '안녕하세요'를 전달하고 함수 내부에서 뒤에 “반갑습니다”를 붙이고 리턴하여 함수 외부에서 출력
      ex04_function_param_return.py
      
      def hello(h):
          return_value = h + "반갑습니다"
          return return_value
      
      param_var = "안녕하세요"
      result = hello(param_var)
      print(result)

02. 사용자 정의 함수, 내장함수

  1. 사용자 정의 함수
    1. 필요한 기능을 개발자가 직접 함수로 정의. 필요할 때마다 호출하여 사용할 수 있음
    2. 함수이름, 매개변수, 실행내용, 리턴값 등을 정의함
  2. 내장함수
    1. 파이썬에서 기본적으로 제공하는 함수
    2. 대표적인 내장함수(일부만 소개)
      ✅input(): 사용자 입력으로 받은 값을 문자열로 반환
      ✅len(): 문자열, 리스트, 튜플, 딕셔너리 등의 길이(항목수)를 반환
      ✅min(): 매개변수로 전달받은 변수의 최솟값을 반환
      ✅max(): 매개변수로 전달받은 변수의 최댓값을 반환
      ✅type(): 변수의 자료형을 반환
      ✅ print(): 매개변수로 전달하는 값 또는 변수 값을 콘솔에 출력

 

 

ch06 파이썬 함수 응용

💡 이번 차시의 학습목표

✔ 이전 차시에서 진행한 예제를 활용하여 다양한 방법으로 함수로 구성하기

 

실습 1) 1부터 100까지 숫자 중에서 3의배수 합계 구하기

  1. 기존 코드를 함수 내부에 정의하고 호출하여 실행하기
    ex01_1to100sum_function_01.py
    
    def sum1():
        sum = 0
        for i in range(1,101):
            if i%3 == 0:
                print(i)
                sum += i
        print("1부터 100까지 3의배수 합은",sum,"입니다")
    
    # 함수호출
    sum1()​


  2. 사용자에게 숫자를 입력 받아 1부터 입력 받은 숫자까지 3의 배수 합계 구하기
    ex01_1to100sum_function_02.py
    
    def sum2(num):
        sum = 0
        for i in range(1,num+1):
            if i%3 == 0:
                print(i)
                sum += i
        print("1부터 ",num,"까지 3의배수 합은",sum,"입니다")
    
    num2 = input("숫자를 입력하세요: ")
    num2 = int(num2)
    sum2(num2)​


  3. 합계 결과를 반환 받아서 출력하기
    ex01_1to100sum_function_03.py
    
    def sum3(num):
        sum = 0
        for i in range(1,num+1):
            if i%3 == 0:
                print(i)
                sum += i
        return sum
    
    num3 = input("숫자를 입력하세요: ")
    num3 = int(num3)
    result3 = sum3(num3)
    print("1부터 ",num3,"까지 3의배수 합은",result3,"입니다")

 

 

 

 

실습 2) 일치하는 이름 찾기

  1. 기존 코드를 함수 내부에 정의하고 호출하여 실행하기
    ex02_findname_function_01.py
    
    def findname1():
        names1 = ["김파이", "이파이", "박파이", "최파이"]
        search_name1 = input("찾아볼 이름을 입력하세요:")
        if search_name1 in names1:
            print("찾는 이름이 있습니다.")
            print(names1.index(search_name1))
        else:     
            print("찾는 이름이 없습니다.")
    
    findname1()


  2. 찾고자 하는 이름을 사용자에게 입력 받아 매개변수로 넘기기
    ex02_findname_function_02.py
    
    def findname2(name2):
        names2 = ["김파이", "이파이", "박파이", "최파이"]
    
        if name2 in names2:
            print("찾는 이름이 있습니다.")
            print(names2.index(search_name2))
        else:     
            print("찾는 이름이 없습니다.")
    
    search_name2 = input("찾아볼 이름을 입력하세요:")
    findname2(search_name2)


  3. 찾고자 하는 이름과 이름 리스트를 매개변수로 넘기기
    ex02_findname_function_03.py
    
    def findname3(name3, names3): 
        if name3 in names3:
            print("찾는 이름이 있습니다.")
            print(names3.index(search_name3))
        else:     
            print("찾는 이름이 없습니다.")
    
    names3 = ["김파이", "이파이", "박파이", "최파이"]
    search_name3 = input("찾아볼 이름을 입력하세요:")
    findname3(search_name3, names3)

 

 

ch07 파이썬 모듈과 모듈 활용

💡 이번 차시의 학습목표

✔ 파이썬 모듈 이해하기

✔ 파이썬 모듈 사용하기

01. 모듈

  1. 함수, 클래스 등을 정의한 파이썬 파일
  2. 다른 파이썬 파일에서 호출하여 사용할 수 있음
  3. 문법
    1. import
      1. 다른 파일에 정의된 함수 변수 등을 모두 사용할 수 있음
      2. 호출할 때는 파일이름.함수이름() 형태로 호출함
      3. as를 이용하여 이름을 줄일 수 있음
      4. import [해당파일이름(.py는 생략)] import [해당파일이름(.py는 생략)] as [약어]
    2. from ~ import ~
      1. 다른 파일의 특정 함수만 지정하여 가져오는 방법
      2. from [해당파일이름(.py는 생략)] import [함수이름]

02. 모듈 연습하기

  1. 모듈 사용시 실행하면 폴더 내에 [✅**pycache]** 라는 폴더가 생성
  2. [✅**pycache]** 폴더는 다음 번 실행시 더 빠른 실행을 위해 파이썬 자체에서 만들어내는 폴더
  3. 하나의 파일에 함수와 호출 문장이 함께 존재
    ex01_main.py
    
    def hello():
        print("안녕하세요")
    
    hello()


  4. 함수와 호출하는 문장이 서로 다른 파일에 존재
    ex02_main.py
    
    import ex02_function as ex
    
    # hello() # 오류
    # ex02_function.hello()
    ex.hello()
    
    ex02_function.py
    
    def hello():
        print("안녕하세요")


  5. 함수가 정의된 파일에 함수가 2개 정의된 경우
    1. 파일 전체 import
      ex03_functions.py
      
      def hello1():
          print("안녕하세요. hello1")
      
      def hello2():
          print("안녕하세요. hello2")
      
      ex03_main.py
      
      import ex03_functions
      
      # hello1() # 오류
      ex03_functions.hello1()
      ex03_functions.hello2()


    2. hello1 함수만 import
      ex04_functions.py
      
      def hello1():
          print("안녕하세요. hello1")
      
      def hello2():
          print("안녕하세요. hello2")
      
      ex04_main.py
      
      from ex03_functions import hello1
      
      hello1()
      # hello2() # 오류


    3. 함수를 모두 import 하고 함수 이름으로만 호출
      ex05_functions.py
      
      def hello1():
          print("안녕하세요. hello1")
      
      def hello2():
          print("안녕하세요. hello2")
      
      ex05_main.py
      
      from ex05_functions import *
      
      hello1()
      hello2()

 

 

 

 

 

 

 

+ Recent posts