谷歌图片爬虫遇ElementClickInterceptedException及图片保存失败求助
问题解决:谷歌图片爬虫的ElementClickInterceptedException与图片保存路径问题
一、ElementClickInterceptedException 异常解决
该异常因目标元素被其他UI元素遮挡(如加载弹窗、未完全加载的元素)导致,可通过以下方式修复:
- 用
WebDriverWait显式等待元素可点击,替代固定time.sleep(),确保元素加载完成后再操作 - 使用JavaScript脚本强制执行点击,绕过页面遮挡判断
- 提前处理页面可能出现的Cookie或隐私政策弹窗
二、图片无法保存到指定文件夹问题
当前代码仅指定文件名,默认保存到当前工作目录,需拼接预先创建的目标文件夹路径,确保图片存入指定位置。
修复后的完整代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import urllib.request import os import sys search = input("검색어: ") # 이미지 이름 target_count = int(input("download counts: ")) # 크롤링할 이미지 개수 save_base = "crawled_images/" # 이미지들을 저장할 폴더 주소 path = os.path.join(save_base, f"{search}_{target_count}") # 중복되는 폴더 명이 없다면 생성 if not os.path.exists(path): os.makedirs(path) # 중복된다면 문구 출력 후 프로그램 종료 else: print('이전에 같은 [검색어, 이미지 수]로 다운로드한 폴더가 존재합니다.') sys.exit(0) ## 셀레니움으로 구글 이미지 접속 후 이미지 검색 options = webdriver.ChromeOptions() #options.add_argument("--headless") options.add_argument("window-size=1920x1080") service = Service(executable_path='chromedriver') driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.google.co.kr/imghp?hl=ko&tab=wi&ogbl") # 处理可能的Cookie弹窗 try: cookie_btn = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ".QS5gu.sy4vM")) ) cookie_btn.click() except: pass elem = driver.find_element(By.NAME, "q") elem.send_keys(search) elem.send_keys(Keys.RETURN) # 페이지 끝까지 스크롤 내리기 SCROLL_PAUSE_TIME = 1 last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(SCROLL_PAUSE_TIME) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: try: # 显式等待"더 보기"按钮可点击 more_btn = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ".LZ4I")) ) more_btn.click() time.sleep(SCROLL_PAUSE_TIME) except: break last_height = new_height # 이미지 찾고 다운받기 images = driver.find_elements(By.CSS_SELECTOR, ".rg_i.Q4LuWd") count = 1 wait = WebDriverWait(driver, 10) for image in images: if count > target_count: break try: # 使用JS脚本点击,避免遮挡问题 driver.execute_script("arguments[0].click();", image) # 等待大图加载完成 img_element = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, ".n3VNCb.KA1RDb")) ) imgUrl = img_element.get_attribute("src") # 拼接完整保存路径 save_path = os.path.join(path, f"{count}.jpg") urllib.request.urlretrieve(imgUrl, save_path) count += 1 except Exception as e: print(f"第{count}张图片爬取失败: {str(e)}") continue driver.close()
关键修改点说明
异常处理优化:
- 添加Cookie弹窗处理逻辑,避免遮挡后续操作
- 对"더 보기"按钮和图片元素使用
WebDriverWait显式等待,提升稳定性 - 采用JavaScript点击方式,绕过元素遮挡问题
路径问题修复:
- 使用
os.path.join()拼接完整保存路径,确保图片存入预先创建的目标文件夹 - 重命名原
count变量为target_count,避免循环中覆盖目标下载数量的变量
- 使用
内容的提问来源于stack exchange,提问作者김도열
相关产品推荐
相关产品推荐

