Selenium爬取谷歌地图:滚动元素至指定文本出现时停止
解决Selenium爬取谷歌地图滚动到列表末尾停止的问题
原代码依赖固定循环次数滚动,无法精准判断列表是否到底。可以通过**检测列表末尾的提示文本"You've reached the end of the list"**来终止滚动,同时设置最大尝试次数避免无限循环。
修正后的代码
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time # 搜索关键词(替换为你的实际关键词) procurar = "contabilidade balneario camboriu" wait = WebDriverWait(driver, 10) # 定位目标滚动容器 scroll_container = wait.until(EC.presence_of_element_located( (By.XPATH, f"//div[@role='main']//div[contains(@aria-label,'{procurar}')]") )) max_attempts = 200 # 最大滚动尝试次数,防止无限等待 current_attempt = 0 while current_attempt < max_attempts: # 滚动到容器底部 driver.execute_script("arguments[0].scrollTo(0, arguments[0].scrollHeight);", scroll_container) current_attempt += 1 time.sleep(1) # 等待页面加载新内容,可根据网络速度调整 try: # 检测是否出现列表末尾提示 end_notice = wait.until(EC.presence_of_element_located( (By.XPATH, '//div[text()="You\'ve reached the end of the list"]') )) print("已滚动至列表末尾,停止操作") break except: # 未检测到末尾提示,继续滚动 continue
关键修改点
- 替换固定循环为条件循环:用
while循环替代for range(100),结合max_attempts避免无限等待 - 添加末尾文本检测:通过XPATH定位包含目标文本的元素,一旦检测到就终止滚动
- 增加加载等待:每次滚动后暂停1秒,确保页面有足够时间加载新的搜索结果
- 异常处理:捕获元素未找到的异常,保证循环能继续执行直到满足终止条件
如果谷歌地图页面的末尾提示元素有特定的class或属性,也可以用更精准的定位方式(比如By.CLASS_NAME)来提高检测稳定性。
内容的提问来源于stack exchange,提问作者Felipe
相关产品推荐
相关产品推荐

