[codeit] 코스타그램 스크래핑 I

SUNGJIN KIM·2021년 12월 9일
0

codeit

목록 보기
15/18

실습

저번 영상에서 설명드렸던 코스타그램 스크래핑을 시작해 봅시다.

이번 과제에서는 아래 동작들에 대한 Selenium 코드를 짜 주세요:

  1. 웹 드라이버 생성 후 코스타그램 접속
  2. 코스타그램 로그인
  3. 웹 페이지 끝까지 스크롤
  4. 각 썸네일(포스팅)을 클릭하고, 창이 뜨면 닫기 버튼 누르기
  5. 웹 드라이버 종료

문제 풀이

코드 작성 시 오류가 나는 부분에 대해서는 아래 벨로그에 정리해놨다.
https://velog.io/@woonmong/DeprecationWarning-executablepath-has-been-deprecated-please-pass-in-a-Service-object-%EC%98%A4%EB%A5%98-%ED%95%B4%EA%B2%B0

이외 나머지 부분에 대해서는 과제 완료!

import time
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

s = Service('{크롬드라이버주소}')

driver = webdriver.Chrome(service=s)
driver.implicitly_wait(3)

driver.get('{코스타그램 주소}')
time.sleep(1)

# 1. 로그인 (codeit/datascience)

driver.find_element(By.CSS_SELECTOR,'a.top-nav__login-link').click()
time.sleep(1)
driver.find_element(By.CSS_SELECTOR,'input.login-container__login-input').send_keys('codeit')
driver.find_element(By.CSS_SELECTOR,'input.login-container__password-input').send_keys('datascience')
time.sleep(1)
driver.find_element(By.CSS_SELECTOR,'input.login-container__login-button').click()
time.sleep(2)

# 2. 끝까지 스크롤
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
    time.sleep(0.5)

    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

# 3. 각 썸네일 클릭 -> 닫기 버튼
post_list = driver.find_elements(By.CSS_SELECTOR,'div.post-list__post')

print(post_list)
for list in post_list:
    list.click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR,'button.close-btn').click()
    time.sleep(1)

# 4. 웹 드라이버 종료
driver.quit()
profile
#QA #woonmong

0개의 댓글