使用Selenium爬取谷歌地图伦敦前五工程学校无结果,求技术排查
谷歌地图Selenium爬取无结果问题排查与修复
问题原因分析
- XPATH语法错误:你直接用
//a[@class='place-result-container-place-link']/@aria-label作为定位表达式,Selenium的find_elements只能定位元素节点,无法直接获取属性值,必须先定位元素再提取属性。 - 过时的元素类名:谷歌地图的页面元素类名会动态更新,
place-result-container-place-link这个类名已经失效,当前搜索结果的链接类名是hfpxzc。 - 硬等待不稳定:
time.sleep()无法精准判断页面加载状态,可能导致元素还未渲染完成就执行查找操作,最终返回空列表。
修复后的代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = Options() chrome_options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=chrome_options) try: # 打开谷歌主页并同意隐私政策 driver.get("https://www.google.com/") WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "L2AGLb")) ).click() # 打开谷歌地图 driver.get("https://www.google.com/maps") # 等待搜索框加载并输入查询 search_box = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, "searchboxinput")) ) search_box.send_keys("engineering school in london") search_box.send_keys(Keys.RETURN) # 等待搜索结果加载完成 WebDriverWait(driver, 15).until( EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div[role='listitem'] a.hfpxzc")) ) # 获取前五条结果的名称 results = driver.find_elements(By.CSS_SELECTOR, "div[role='listitem'] a.hfpxzc") for i, result in enumerate(results[:5], start=1): school_name = result.get_attribute("aria-label") print(f"Result {i}: {school_name}") finally: # 确保浏览器关闭 driver.quit()
关键修复点说明
- 改用显式等待:使用
WebDriverWait配合expected_conditions,确保元素可交互或可见后再执行操作,比硬等待更稳定可靠。 - 修正元素定位:使用当前有效的CSS选择器
div[role='listitem'] a.hfpxzc定位结果链接,再通过get_attribute('aria-label')提取名称。 - 异常处理:用
try...finally结构确保无论程序是否出错,浏览器都会正常关闭,避免资源泄漏。
内容的提问来源于stack exchange,提问作者bouchkira ilias
相关产品推荐
相关产品推荐

