
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
안녕하세요. 4주차 숙제 제출 시 정확하게 코드를 입력했지만 일부분 애러로 인해 엑셀 파일은 만들지 못했습니다. 어느 부분인 error인지 확인 부탁드립니다.
(.venv) C:\Users\heaha\Desktop\automation\python_pratice>c:/Users/heaha/Desktop/automation/python_pratice/.venv/Scripts/python.exe c:/Users/heaha/Desktop/automation/python_pratice/crawling/excel_crawling.py
Traceback (most recent call last):
File "c:\Users\heaha\Desktop\automation\python_pratice\crawling\excel_crawling.py", line 19, in <module>
search = driver.find_element(By.CSS_SELECTOR, "input._searchInput_search_text_3CUDs")
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 738, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 344, in execute
self.error_handler.check_response(response)
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"input._searchInput_search_text_3CUDs"}
(Session info: chrome=127.0.6533.100); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Stacktrace:
GetHandleVerifier [0x00007FF64AE59632+30946]
(No symbol) [0x00007FF64AE0E3C9]
(No symbol) [0x00007FF64AD06FDA]
(No symbol) [0x00007FF64AD5822C]
(No symbol) [0x00007FF64AD5850C]
(No symbol) [0x00007FF64AD9DCB7]
(No symbol) [0x00007FF64AD7CAAF]
(No symbol) [0x00007FF64AD9B041]
(No symbol) [0x00007FF64AD7C813]
(No symbol) [0x00007FF64AD4A6E5]
(No symbol) [0x00007FF64AD4B021]
GetHandleVerifier [0x00007FF64AF8F83D+1301229]
GetHandleVerifier [0x00007FF64AF9BDB7+1351783]
GetHandleVerifier [0x00007FF64AF92A03+1313971]
GetHandleVerifier [0x00007FF64AE8DD06+245686]
(No symbol) [0x00007FF64AE1758F]
(No symbol) [0x00007FF64AE13804]
(No symbol) [0x00007FF64AE13992]
(No symbol) [0x00007FF64AE0A3EF]
BaseThreadInitThunk [0x00007FF824777374+20]
RtlUserThreadStart [0x00007FF824B1CC91+33]
(.venv) C:\Users\heaha\Desktop\automation\python_pratice>c:/Users/heaha/Desktop/automation/python_pratice/.venv/Scripts/python.exe c:/Users/heaha/Desktop/automation/python_pratice/crawling/excel_crawling.py
Traceback (most recent call last):
File "c:\Users\heaha\Desktop\automation\python_pratice\crawling\excel_crawling.py", line 19, in <module>
search = driver.find_element(By.CSS_SELECTOR, "input._searchInput_search_text_3CUDs")
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 738, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 344, in execute
self.error_handler.check_response(response)
File "c:\Users\heaha\Desktop\automation\python_pratice\.venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"input._searchInput_search_text_3CUDs"}
(Session info: chrome=127.0.6533.100); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Stacktrace:
GetHandleVerifier [0x00007FF64AE59632+30946]
(No symbol) [0x00007FF64AE0E3C9]
(No symbol) [0x00007FF64AD06FDA]
(No symbol) [0x00007FF64AD5822C]
(No symbol) [0x00007FF64AD5850C]
(No symbol) [0x00007FF64AD9DCB7]
(No symbol) [0x00007FF64AD7CAAF]
(No symbol) [0x00007FF64AD9B041]
(No symbol) [0x00007FF64AD7C813]
(No symbol) [0x00007FF64AD4A6E5]
(No symbol) [0x00007FF64AD4B021]
GetHandleVerifier [0x00007FF64AF8F83D+1301229]
GetHandleVerifier [0x00007FF64AF9BDB7+1351783]
GetHandleVerifier [0x00007FF64AF92A03+1313971]
GetHandleVerifier [0x00007FF64AE8DD06+245686]
(No symbol) [0x00007FF64AE1758F]
(No symbol) [0x00007FF64AE13804]
(No symbol) [0x00007FF64AE13992]
(No symbol) [0x00007FF64AE0A3EF]
BaseThreadInitThunk [0x00007FF824777374+20]
RtlUserThreadStart [0x00007FF824B1CC91+33]보고 계신 화면 전체를 캡처해 주시면, 튜터님들이 빠르게 상황을 이해할 수 있어요.
작성한 코드 및 에러 메세지
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import requests
from io import BytesIO
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.styles import PatternFill, Alignment
# 크롬 드라이버 옵션 설정
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(options=chrome_options)
# 검색창에 '후드티' 입력하고 검색 실행
search = driver.find_element(By.CSS_SELECTOR, "input._searchInput_search_text_3CUDs")
search.click()
search.send_keys("아이폰")
search.send_keys(Keys.ENTER)
# 스크롤 전 높이
before_h = driver.execute_script("return window.scrollY")
# 무한 스크롤
while True:
# 맨 아래로 스크롤 내린다.
driver.find_element(By.CSS_SELECTOR, "body").send_keys(Keys.END)
# 스크롤 사이 페이지 로딩 시간
time.sleep(1)
# 스크롤 후 높이
after_h = driver.execute_script("return window.scrollY")
if after_h == before_h:
break
before_h = after_h
# 새 워크북 생성 및 시트 활성화
wb = Workbook()
ws = wb.active
ws.title = "상품 정보"
# 헤더 행 추가
ws.append(['상품명', '가격', '링크', '총 리뷰 수', '이미지'])
# 상품 정보 수집
items = driver.find_elements(By.CSS_SELECTOR, ".searchInput_search_text_3CUDs")
for item in items:
# 상품명 찾기
names = item.find_elements(By.CSS_SELECTOR, ".adProduct_title__amInq")
name = names[0].text if names else "이름 없음"
# 가격 찾기
prices = item.find_elements(By.CSS_SELECTOR, ".price_num__S2p_v")
price = prices[0].text if prices else "가격 없음"
# 링크 찾기
links = item.find_elements(By.CSS_SELECTOR, ".adProduct_title__amInq > a")
link = links[0].get_attribute('href') if links else "링크 없음"
# 리뷰 수 찾기
review_totals = item.find_elements(By.CSS_SELECTOR, ".product_num__fafe5")
review_total = review_totals[0].text if review_totals else "리뷰 없음"
# 이미지 찾기
images = item.find_elements(By.CSS_SELECTOR, '.thumbnail_btn_box____IiP')
image = images[0].get_attribute('src') if images else "이미지 없음"
ws.append([name, price, link, review_total, image])
col_num = 5
for row_num, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
img_url = row[col_num-1] # E열의 이미지 URL
if img_url: # 이미지 URL이 있다면
try:
response = requests.get(img_url) # 이미지 URL로부터 이미지 다운로드
img = Image(BytesIO(response.content)) # 이미지 객체 생성
img.width = 140
img.height = 140
cell = ws.cell(row=row_num, column=col_num)
cell.value = "" # 기존의 이미지 URL을 비움
ws.add_image(img, f'E{row_num}') # 이미지 삽입 위치 지정
ws.row_dimensions[row_num].height = 140 # 셀 높이 조정
except Exception as e:
print(f"{e}")
# 회색 배경색 설정
color = PatternFill(start_color='FFA07A', end_color='FFA07A', fill_type='solid')
for row in ws.iter_rows(min_row=1, max_row=1): # 첫 번째 행에 적용 (데이터 제목 행)
for cell in row:
cell.fill = color
# 열 너비 변경
ws.column_dimensions['A'].width = 30
ws.column_dimensions['E'].width = 20
# 수직 가운데 맞춤 설정
for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
for cell in row:
cell.alignment = Alignment(vertical="center")
# Excel 파일 저장
excel_file_path = "상품 정보.xlsx"
wb.save(excel_file_path)
# 웹드라이버 종료
driver.quit()
오류 발생 시, 작성한 코드 전체와 에러 메시지를 첨부해 주세요.
Tip 1) </> 아이콘을 눌러 코드박스를 만들어 보세요.
Tip 2) Ctrl+A(맥의 경우 Command+A) 단축키로 코드를 한 번에 선택할 수 있어요!
