0

0

使用Selenium高效抓取Google地图完整评论:处理“更多”按钮与动态加载

花韻仙語

花韻仙語

发布时间:2025-12-13 13:12:53

|

153人浏览过

|

来源于php中文网

原创

使用selenium高效抓取google地图完整评论:处理“更多”按钮与动态加载

本教程详细介绍了如何利用Selenium自动化浏览器抓取Google地图上的商家评论。文章聚焦于解决动态加载评论(通过滚动)和处理被截断的评论(点击“更多”按钮)两大挑战。通过提供清晰的步骤、示例代码和最佳实践,旨在帮助读者构建一个稳定、高效的评论抓取解决方案,确保获取到每一条评论的完整内容。

1. 引言:Google地图评论抓取的挑战

Google地图的评论页面通常采用动态加载机制,这意味着初始页面仅显示部分评论。用户需要滚动页面才能加载更多评论。此外,为了保持页面简洁,较长的评论会被截断,显示一个“更多”按钮。要获取这些评论的完整内容,必须模拟点击这些“更多”按钮。本教程将详细讲解如何使用Python和Selenium库应对这些挑战,实现Google地图评论的全面抓取。

2. 环境准备与Selenium基础配置

在开始之前,请确保您的Python环境中已安装Selenium库和对应浏览器(如Chrome)的WebDriver。

pip install selenium webdriver-manager

初始化WebDriver

我们将使用Chrome浏览器进行演示。webdriver-manager库可以帮助我们自动管理ChromeDriver的版本。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
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.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException
import time

# 目标Google地图商家评论页面的URL
# 请替换为你要抓取的实际URL
TARGET_URL = 'https://www.google.com/maps/place/Henn+na+Hotel+Tokyo+Asakusa+Tawaramachi/@35.7081692,139.7888494,17z/data=!4m22!1m12!3m11!1s0x60188f36ab21f05b:0x9241dab287ff62c9!2sHenn+na+Hotel+Tokyo+Asakusa+Tawaramachi!5m2!4m1!1i2!8m2!3d35.7081692!4d139.7914243!9m1!1b1!16s%2Fg%2F11h0gzlhht!3m8!1s0x60188f36ab21f05b:0x9241dab287ff62c9!5m2!4m1!1i2!8m2!3d35.7081692!4d139.7914243!16s%2Fg%2F11h0gzlhht?entry=ttu'

# 配置Chrome选项
chrome_options = Options()
# chrome_options.add_argument('--headless') # 无头模式运行,不显示浏览器界面
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--start-maximized') # 启动时最大化窗口,确保元素可见

# 初始化WebDriver
driver = webdriver.Chrome(options=chrome_options)
driver.get(TARGET_URL)

3. 处理Cookie同意弹窗

许多网站在首次访问时会显示Cookie同意弹窗。我们需要识别并点击同意按钮以继续。

喜鹊标书
喜鹊标书

AI智能标书制作平台,10分钟智能生成20万字投标方案,大幅提升中标率!

下载
def accept_cookie_policy(driver):
    """尝试点击Cookie同意按钮。"""
    try:
        # 等待页面加载,并尝试找到“Accept all”按钮
        # 寻找所有按钮,然后通过文本内容筛选
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'button'))
        )
        buttons = driver.find_elements(By.TAG_NAME, 'button')
        for button in buttons:
            if "Accept all" in button.text: # 使用in操作符更健壮
                print("点击 'Accept all' Cookie按钮。")
                button.click()
                time.sleep(2) # 等待弹窗消失
                return True
    except TimeoutException:
        print("未找到或无法点击Cookie政策按钮。")
    except Exception as e:
        print(f"处理Cookie时发生错误: {e}")
    return False

accept_cookie_policy(driver)

4. 导航至评论区

在某些Google地图页面中,评论可能不是默认显示的。我们需要找到并点击“评论”选项卡或按钮。

def navigate_to_reviews(driver):
    """导航到评论区。"""
    try:
        # 等待页面加载,并找到“Reviews”按钮
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'button'))
        )
        all_buttons = driver.find_elements(By.TAG_NAME, 'button')
        for button in all_buttons:
            if "Reviews" in button.text:
                print("点击 'Reviews' 按钮。")
                button.click()
                time.sleep(3) # 等待评论区加载
                return True
    except TimeoutException:
        print("未找到 'Reviews' 按钮。")
    except Exception as e:
        print(f"导航到评论区时发生错误: {e}")
    return False

navigate_to_reviews(driver)

5. 滚动加载所有评论

这是获取所有评论的关键一步。我们需要找到评论区的可滚动容器,并模拟滚动操作,直到所有评论都被加载。

def scroll_to_load_all_reviews(driver):
    """滚动评论区以加载所有评论。"""
    print("开始滚动加载所有评论...")
    # Google Maps评论的滚动容器通常具有特定的class或aria-label
    # 经过观察,评论列表本身是一个可滚动区域,其父级可能是一个具有特定样式的div
    # 尝试找到评论列表的父级滚动容器,这里使用一个常见的类名组合
    # 如果这个选择器失效,需要根据实际页面结构调整
    try:
        # 查找包含评论的滚动容器。这里假定评论列表的直接父元素是可滚动的。
        # 实际的Google Maps页面结构可能会有所不同,可能需要更精确的定位。
        # 示例中使用的类名 'm6QErb' 'DxyBCb' 'kA9KIf' 'dS8AEf' 是一个常见的组合,但可能变化。
        # 更稳健的方法可能是寻找一个具有 `role="feed"` 或 `aria-label="Reviews"` 的元素。
        review_scroll_container = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'm6QErb') and contains(@class, 'DxyBCb') and contains(@class, 'kA9KIf') and contains(@class, 'dS8AEf')]"))
        )
    except TimeoutException:
        print("未找到评论滚动容器,请检查XPath或页面结构。")
        return

    last_height = driver.execute_script("return arguments[0].scrollHeight", review_scroll_container)

    while True:
        # 模拟滚动到底部
        driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", review_scroll_container)
        time.sleep(3) # 等待新内容加载

        new_height = driver.execute_script("return arguments[0].scrollHeight", review_scroll_container)
        if new_height == last_height:
            # 如果滚动高度没有变化,说明已经到达底部
            print("所有评论已加载。")
            break
        last_height = new_height

    # 滚动到顶部,确保所有元素在视口内以便后续操作(可选,但有时有用)
    driver.execute_script("arguments[0].scrollTop = 0", review_scroll_container)
    time.sleep(2)

scroll_to_load_all_reviews(driver)

6. 展开并提取完整评论

在所有评论加载完成后,我们需要遍历每一条评论,检查是否存在“更多”按钮,如果存在则点击它,然后提取完整的评论文本。

def extract_full_reviews(driver):
    """展开所有“更多”按钮并提取完整评论。"""
    print("开始展开评论并提取内容...")
    all_reviews_data = []

    # 查找所有评论容器。Google Maps中每个评论通常在一个具有特定类名的div中。
    # 'jftiEf' 是一个常见的评论容器类名。
    review_elements = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, 'jftiEf'))
    )

    print(f"找到 {len(review_elements)} 条评论容器。")

    for i, review_element in enumerate(review_elements):
        try:
            # 尝试在当前评论容器内查找“More”按钮
            # 'w8nwRe' 是“More”按钮的常见类名
            more_button = review_element.find_element(By.CLASS_NAME, "w8nwRe")
            if "More" in more_button.text: # 再次确认文本是“More”
                more_button.click()
                time.sleep(1) # 点击后等待内容展开
                print(f"点击了第 {i+1} 条评论的 'More' 按钮。")
        except NoSuchElementException:
            # 没有“More”按钮,评论已是完整内容
            pass
        except StaleElementReferenceException:
            # 元素过时,通常是因为页面内容发生变化,尝试重新定位
            print(f"第 {i+1} 条评论的元素过时,尝试重新定位...")
            review_elements = WebDriverWait(driver, 5).until(
                EC.presence_of_all_elements_located((By.CLASS_NAME, 'jftiEf'))
            )
            # 重新获取当前评论元素并重试
            try:
                review_element = review_elements[i]
                more_button = review_element.find_element(By.CLASS_NAME, "w8nwRe")
                if "More" in more_button.text:
                    more_button.click()
                    time.sleep(1)
                    print(f"重新点击了第 {i+1} 条评论的 'More' 按钮。")
            except Exception as e:
                print(f"重新处理第 {i+1} 条评论时仍然出错: {e}")
                pass # 忽略错误,继续下一条

        # 提取评论的完整文本
        # 'wiI7pd' 可能是包含评论文本的元素
        try:
            review_text_element = review_element.find_element(By.CLASS_NAME, 'wiI7pd')
            full_review_text = review_text_element.text
            all_reviews_data.append(full_review_text)
        except NoSuchElementException:
            print(f"未找到第 {i+1} 条评论的文本内容元素。")
            all_reviews_data.append("评论文本未找到") # 记录缺失
        except Exception as e:
            print(f"提取第 {i+1} 条评论文本时发生错误: {e}")
            all_reviews_data.append(f"提取失败: {e}")

    return all_reviews_data

# 执行提取
reviews = extract_full_reviews(driver)

# 打印结果
print("\n--- 抓取到的完整评论 ---")
for idx, review in enumerate(reviews):
    print(f"评论 {idx+1}:\n{review}\n---")

# 关闭浏览器
driver.quit()

7. 完整代码示例

将上述所有步骤整合,形成一个完整的评论抓取脚本:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
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.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException
import time
import csv

# 目标Google地图商家评论页面的URL
TARGET_URL = 'https://www.google.com/maps/place/Henn+na+Hotel+Tokyo+Asakusa+Tawaramachi/@35.7081692,139.7888494,17z/data=!4m22!1m12!3m11!1s0x60188f36ab21f05b:0x9241dab287ff62c9!2sHenn+na+Hotel+Tokyo+Asakusa+Tawaramachi!5m2!4m1!1i2!8m2!3d35.7081692!4d139.7914243!9m1!1b1!16s%2Fg%2F11h0gzlhht!3m8!1s0x60188f36ab21f05b:0x9241dab287ff62c9!5m2!4m1!1i2!8m2!3d35.7081692!4d139.7914243!16s%2Fg%2F11h0gzlhht?entry=ttu'

def initialize_driver():
    """初始化Chrome WebDriver并返回实例。"""
    chrome_options = Options()
    # chrome_options.add_argument('--headless') # 无头模式运行,不显示浏览器界面
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--start-maximized') # 启动时最大化窗口,确保元素可见
    chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124124 Safari/537.36")

    driver = webdriver.Chrome(options=chrome_options)
    driver.get(TARGET_URL)
    return driver

def accept_cookie_policy(driver):
    """尝试点击Cookie同意按钮。"""
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'button'))
        )
        buttons = driver.find_elements(By.TAG_NAME, 'button')
        for button in buttons:
            if "Accept all" in button.text:
                print("点击 'Accept all' Cookie按钮。")
                button.click()
                time.sleep(2)
                return True
    except TimeoutException:
        print("未找到或无法点击Cookie政策按钮。")
    except Exception as e:
        print(f"处理Cookie时发生错误: {e}")
    return False

def navigate_to_reviews(driver):
    """导航到评论区。"""
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'button'))
        )
        all_buttons = driver.find_elements(By.TAG_NAME, 'button')
        for button in all_buttons:
            if "Reviews" in button.text:
                print("点击 'Reviews' 按钮。")
                button.click()
                time.sleep(3)
                return True
    except TimeoutException:
        print("未找到 'Reviews' 按钮。")
    except Exception as e:
        print(f"导航到评论区时发生错误: {e}")
    return False

def scroll_to_load_all_reviews(driver):
    """滚动评论区以加载所有评论。"""
    print("开始滚动加载所有评论...")
    try:
        review_scroll_container = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'm6QErb') and contains(@class, 'DxyBCb') and contains(@class, 'kA9KIf') and contains(@class, 'dS8AEf')]"))
        )
    except TimeoutException:
        print("未找到评论滚动容器,请检查XPath或页面结构。")
        return

    last_height = driver.execute_script("return arguments[0].scrollHeight", review_scroll_container)

    while True:

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

760

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

639

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

762

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

618

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1265

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

549

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

579

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

709

2023.08.11

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

72

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 4.5万人学习

Django 教程
Django 教程

共28课时 | 3.2万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号