You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过Selenium Python点击Google Trends页面的Explore文本求助

解决Google Trends自动化访问与Selenium点击失败问题

一、先解决Google的自动化检测拦截

Google Trends对Selenium这类自动化工具的检测很严格,你的现有配置不足以绕过检测,需要添加更多反检测参数:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC  # 修正你代码里的ES拼写错误

chrome_options = Options()
# *核心反检测配置*
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--window-size=1920x1080")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")  # 禁用自动化控制标记,避免被检测
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 移除Chrome的自动化提示栏
chrome_options.add_experimental_option('useAutomationExtension', False)  # 禁用自带的自动化扩展

driver = webdriver.Chrome(options=chrome_options)
# 额外注入JS隐藏webdriver属性,彻底规避检测
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

url = "https://trends.google.com/trends/"
driver.get(url)

二、修复Explore按钮定位失败问题

你之前的XPATH仅定位了文本所在的span,但实际可点击的是外层button元素,且页面可能存在多个含"Explore"的元素,需精准定位:

# 等待按钮可点击(优先定位包含目标span的button)
explore_button = WebDriverWait(driver, 15).until(
    EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Explore']]"))
)
explore_button.click()

如果上述定位仍失效,直接用浏览器开发者工具查看按钮的data-testid或类名,比如:

# 通过data-testid定位(需根据实际页面元素调整值)
explore_button = WebDriverWait(driver, 15).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-testid='explore-button']"))
)

三、更稳定的替代方案:避开Selenium用API包装

如果Selenium仍频繁被封,推荐使用pytrends(Google Trends官方接口的Python包装库),搭配模拟真实请求的配置:

  1. 安装依赖:pip install pytrends
  2. 代码示例(获取印度区域的趋势数据):
from pytrends.request import TrendReq
import time
import random

# 模拟真实浏览器请求头,避免被识别为爬虫
pytrend = TrendReq(
    hl='en-GB',
    tz=330,  # 印度时区(UTC+5:30)
    timeout=(10, 25),
    retries=2,
    backoff_factor=0.1,
    requests_args={'headers': {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
    }}
)

# 获取过去30天的数据
pytrend.build_payload(kw_list=["your-target-keyword"], timeframe='today 1-m', geo='IN')
month_data = pytrend.interest_over_time()
print(month_data)

# 添加随机延迟,避免触发频率限制
time.sleep(random.uniform(1, 3))

# 获取过去12个月的数据
pytrend.build_payload(kw_list=["your-target-keyword"], timeframe='today 12-m', geo='IN')
year_data = pytrend.interest_over_time()
print(year_data)

额外注意事项

  • 不要短时间内频繁请求,Google会根据IP和请求频率触发验证码或临时封禁
  • 若坚持用Selenium,可添加随机滚动、点击等模拟用户行为的操作,或使用代理IP切换会话
  • 定期检查Google Trends页面元素变化,页面更新会导致定位规则失效

内容的提问来源于stack exchange,提问作者Rahim T.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:07:21