짬내서 나홀로 - 크롤링(네이버 영화 순위 평점순)

테리·2022년 7월 22일
0

짬내서 나홀로

목록 보기
3/3
post-thumbnail

사전 단계는 이전 내용과 똑같으니 코드만 나열하고 패스

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import pandas as pd

#영화 랭킹 클릭
driver.find_element('xpath','//*[@id="scrollbar"]/div[1]/div/div/ul/li[3]/a').click()
#평점순 항목 클릭
driver.find_element('xpath','//*[@id="old_content"]/div[1]/ul/li[2]/a/img').click()

이번에는 except 부분을 이전 코드와 조금은 다르게 했다.
그 이유는 평점 또한 중복될 가능성이 있는데 여기서 이전 방식대로 예외 처리를 하게 되면

-> 영화A 평점 : 9
-> 영화B 평점 : 9
-> 예외 처리된 부분에 대체되는 평점 : 9
와 같은 경우의 수가 발생할 수 있다.

그렇기에 이전의 방식대로 중복제거를 하게되면 예외 처리로 발생한 평점 뿐만 아니라 영화B or 영화A의 평점까지 없어지는 문제가 발생한다.

그래서 예외처리하는 except NoSuchElementException: 부분의 코드를 기존에 예외가 되었을 때 출력만 하는 방식이 아니라 리스트에 특정값을 형성해 주는 방식으로 바꾸었다.

for i in range(1,36):
    try:
        movie_name = driver.find_element('xpath','//*[@id="old_content"]/table/tbody/tr['+str(i)+']/td[2]/div/a').text
        movie_score = driver.find_element('xpath','//*[@id="old_content"]/table/tbody/tr['+str(i)+']/td[4]').text
        print(movie_name, movie_score)
    except NoSuchElementException:
        movie_name = '---'
        movie_score = '---'
        print(movie_name, movie_score)

이제 pandas의 DataFrame을 활용하기 위해 리스트 형식으로 다시 정리하면

product_list = []
product_score = []

for i in range(1,36):
    try:
        movie_name = driver.find_element('xpath','//*[@id="old_content"]/table/tbody/tr['+str(i)+']/td[2]/div/a').text
        movie_score = driver.find_element('xpath','//*[@id="old_content"]/table/tbody/tr['+str(i)+']/td[4]').text
        print(movie_name, movie_score)
    except NoSuchElementException:
        movie_name = 'null'
        movie_score = 'null'
        print(movie_name, movie_score)
    product_list.append(movie_name)
    product_score.append(movie_score)

예외 처리된 값을 movie_score에 지정해서 넣어줬기 때문에 유사하지만 조금은 다른 중복 제거 방식을 사용해야한다

#영화 제목중에서 null로 표기된 값만 제거
for list1 in product_list:
    if list1 == 'null':
        product_list.remove('null')

#평점중에서 null로 표기된 값만 제거
for list2 in product_score:
    if list2 == 'null':
        product_score.remove('null')

마지막으로

index_list = list(range(1,32)) #기본 index를 사용하면 0부터 시작하기에 1부터 시작하는 index로 변경
pd.DataFrame({'영화 제목': product_list, '평점': product_score}, index = index_list)

profile
영화 좋아합니다

0개의 댓글