如何循环点击Google Maps评论的More按钮并解决Stale Element Error?
解决Google Maps评论"More"按钮点击的Stale Element Error问题
嘿,我懂你遇到的麻烦——Stale Element Error本质是页面动态更新后,你之前获取的元素引用已经失效了。你原来的代码一次性抓取了所有"More"按钮,但滚动加载评论的过程中,页面可能会重新渲染部分元素,导致这些旧的引用没法再被使用。
下面是调整后的脚本,核心思路是每次只定位并点击一个可操作的"More"按钮,点击完成后重新查找下一个,直到没有更多可点击的按钮为止:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import StaleElementReferenceException, ElementClickInterceptedException, TimeoutException link = "https://www.google.com/maps/place/Pizzeria+Di+Matteo/@40.8512552,14.255779,17z/data=!4m7!3m6!1s0x133b0841ef6e38e5:0xece6ea09987e9baf!8m2!3d40.8512512!4d14.2579677!9m1!1b1" driver = webdriver.Chrome() driver.get(link) wait = WebDriverWait(driver, 10) # 第一步:滚动加载所有评论 while True: try: # 等待加载 spinner 出现,滚动到它的位置触发更多评论加载 elem = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[class='section-loading-spinner']"))) driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", elem) # 给页面一点加载缓冲时间 driver.implicitly_wait(2) except Exception: print("所有评论已加载完成") break # 第二步:循环点击所有"More"按钮,规避Stale Element问题 while True: try: # 每次都重新查找第一个可点击的"More"按钮,避免使用过期引用 see_more_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class^='section-expand-review']"))) # 用JS点击绕开元素被遮挡的问题 driver.execute_script("arguments[0].click();", see_more_btn) # 等待评论展开的缓冲时间 driver.implicitly_wait(1) except (StaleElementReferenceException, ElementClickInterceptedException, TimeoutException): # 没有更多可点击的按钮时退出循环 print("所有评论已展开") break # 第三步:提取完整评论内容 reviews = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".section-review-content"))) for item in reviews: try: name = item.find_element(By.CSS_SELECTOR, "[class='section-review-title'] > span").text review_text = item.find_element(By.CSS_SELECTOR, "[class='section-review-text']").text print(f"用户: {name}\n评论: {review_text}\n---") except Exception as e: print(f"提取评论时出错: {str(e)}") continue driver.quit()
关键改动说明:
- 放弃一次性抓取所有按钮:每次循环都重新定位第一个可点击的"More"按钮,彻底避免使用过期的元素引用。
- 改用JS点击:直接调用
click()有时会遇到元素被其他元素遮挡的问题,用execute_script点击的稳定性更高。 - 捕获多类异常:除了
StaleElementReferenceException,还处理了ElementClickInterceptedException(元素被遮挡)和TimeoutException(无更多按钮),让脚本更健壮。 - 增加缓冲等待:滚动和点击后添加短暂的隐式等待,确保页面元素有足够时间完成更新。
这样调整后,脚本就能顺利展开所有需要点击"More"的评论,同时避开Stale Element Error的坑啦!
内容的提问来源于stack exchange,提问作者MITHU
相关产品推荐
相关产品推荐

