수정 전 기존에 작성했던 코드
# 크롬창(웹드라이버) 열기
driver = webdriver.Chrome('C:/Users/sooyeon/Downloads/chromedriver.exe')
driver.get("https://movie.daum.net/moviedb/grade?movieId=126143")
time.sleep(2)
result = [] #
# 영화 제목 (수집할 데이터는 get에서 받은 영화제목 단 하나이기때문에 굳이 리스트로 받을 필요가 없이 문자열로 받으셔도 충분합니다. )
title = driver.find_element_by_css_selector("#mainContent > div > div.box_basic > div.info_detail > div.detail_tit > h3 > span.txt_tit").text
# 출력되는 값이 있는지?
print(title)
# 리뷰 클릭
driver.find_element_by_xpath('//*[@id="mainContent"]/div/div[2]/div[1]/ul/li[4]/a/span').click()
time.sleep(3)
for i in range(2) :
driver.find_element_by_xpath('''//*[@id="alex-area"]/div/div/div/div[3]/div[1]/button''').click()
time.sleep(1.5)
try:
boxes = driver.find_elements_by_css_selector("#alex-area > div > div > div > div.cmt_box > ul.list_comment > li") # 리뷰 더보기가 끝났다면 box들을 수집해봅시다.
# 리뷰의 박스들을 의미합니다. 몇개나 출력되는지 확인해주세요
# print(boxes)
score = [] # 평점
review = [] # 리뷰
date = [] # 작성일
# 박스를 돌면서 평점, 리뷰, 작성일을 수집합니다.
for box in boxes:
score.append(box.find_element_by_css_selector("li > div > div.ratings").text)
date.append(box.find_element_by_css_selector("li > div > strong > span > span.txt_date").text)
reviewpre = box.find_element_by_css_selector("li > div > p").text
reviewpre = reviewpre.replace('\n','')
review.append(reviewpre)
df = pd.DataFrame({'score': score, 'date':date,'review':review})
df['title'] = title
df.head()
result.append(df)
# 예외 처리
except NoSuchElementException:
continue
except IndexError:
continue
except AttributeError:
continue
except ValueError:
continue
except InvalidSelectorException:
continue
데이터 프레임이 생성되지 않았고 ValueError문제가 발생
확인
값은 잘 저장되어 있으며, score, date, review 모두 같은 리스트 형식임을 확인하였다.
참고 코드
df = pd.DataFrame.from_dict(a, orient='index')
수정
df = pd.DataFrame.from_dict({'score': score, 'date':date,'review':review},orient='index').T
df['title'] = title
df.head()
result.append(df)
오류 해결
ValueError: arrays must all be same length while converting dictionary to data frame
While converting dictionary to pd.dataframe I got the error a = { 'var1': [ 'LPES', 'A' ], 'var2': [ 'F', 'D' ], 'var3': [ 'R', 'T', 'EDUCATION', 'A', ...
stackoverflow.com
추가로 찾아본 문서
Intro to data structures — pandas 1.3.3 documentation
Intro to data structures We’ll start with a quick, non-comprehensive overview of the fundamental data structures in pandas to get you started. The fundamental behavior about data types, indexing, and axis labeling / alignment apply across all of the obje
pandas.pydata.org