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

如何使用Python的Selenium点击指定页面的Vote按钮?

问题描述

我尝试用CSS选择器、XPath和类名点击页面中的「Vote」按钮,目标页面链接:https://birminghamhomeandgarden.com/fresh-kitchen-photo-contest-2023/#/rounds/1/gallery/372301007/

我的代码如下:

# Import the necessary modules
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from time import sleep

from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

ser = Service(r"C:\Users\blah\Documents\Selenium\chromedriver.exe")

driver = webdriver.Chrome(service=ser)
driver.maximize_window()

# Set the URL we want to visit
url = "https://birminghamhomeandgarden.com/fresh-kitchen-photo-contest-2023/#/rounds/1/gallery/372301007/"
driver.get(url)
sleep(10)
votebtn = WebDriverWait(driver, 1000).until((EC.element_to_be_selected(By.XPATH, "//*[@id='ember311']/div[1]/div[2]/div[2]/button")))
votebtn.click()

请指导我如何成功点击该按钮。


解决方案

你的代码存在两个核心问题,修正后即可正常触发按钮点击:

1. 错误的等待条件

EC.element_to_be_selected() 仅针对单选框、复选框这类可选中的表单元素设计,普通操作按钮应该使用 EC.element_to_be_clickable()——它会等待元素可见且可交互,这是点击操作的正确前置条件。

2. 不可靠的定位逻辑

你使用的XPath包含动态生成的ID(ember311),这类ID会随页面加载、会话变化而改变,无法稳定定位元素。推荐以下几种更可靠的定位方式:

方式一:通过按钮文本定位(最直观)

直接匹配按钮上的「Vote」文本,无需依赖易变的元素属性:

votebtn = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Vote')]"))
)
votebtn.click()

方式二:通过按钮类名定位

打开浏览器开发者工具(F12)查看Vote按钮的类名(通常会有类似 vote-btn、btn-primary-vote 这类标识),用类名定位:

votebtn = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.CLASS_NAME, "vote-btn"))
)
votebtn.click()

方式三:通过父元素层级定位

如果按钮的父容器有稳定的属性(比如固定类名),可以基于父元素构造XPath,避开动态ID:

# 示例:假设按钮在class为"gallery-action-bar"的容器内
votebtn = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.XPATH, "//div[@class='gallery-action-bar']/button"))
)
votebtn.click()

额外优化点

  • 移除冗余的 sleep(10):显式等待(WebDriverWait)已经能精准等待元素加载,硬编码等待会降低代码效率和稳定性。
  • 改用 webdriver-manager 自动管理ChromeDriver,避免手动维护驱动路径:
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    

内容的提问来源于stack exchange,提问作者muyfantastico

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:57:45