如何用Selenium点击IMDb指定评分按钮?解决元素点击拦截问题
解决IMDb评分按钮点击被拦截的问题
问题根源
目标评分按钮被上层的ipc-starbar__touch元素遮挡,常规click()方法无法触发按钮本身的点击事件,反而会触发遮挡元素的默认6分操作。
可行解决方案
以下方法支持点击任意指定评分,同时解决遮挡问题:
1. 用JavaScript直接触发点击
JavaScript点击不受元素遮挡影响,能直接调用目标按钮的点击逻辑。配合显式等待替代固定sleep,确保元素加载完成后再操作,提升稳定性。
2. 动态生成评分定位表达式
根据传入的评分值,动态构造aria-label的定位条件,实现任意评分的精准定位。
修改后的代码示例
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def rate_movie(self, url, rate=1): self.get(url) self.maximize_window() # 等待并点击打开评分面板的按钮 movie_name = WebDriverWait(self, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'sc-b73cd867-0.cEmnhL')) ).text open_rate = WebDriverWait(self, 10).until( EC.element_to_be_clickable((By.XPATH, OPEN_RATE_BTN.format(movie_name))) ) open_rate.click() # 等待目标评分按钮加载,动态构造定位路径 target_rate_btn = WebDriverWait(self, 10).until( EC.presence_of_element_located((By.XPATH, f'//button[@aria-label="Rate {rate}"]')) ) # 执行JS点击绕过遮挡 self.execute_script("arguments[0].click();", target_rate_btn)
补充方案(若JS点击仍有问题)
可以先隐藏遮挡元素再点击:
# 隐藏遮挡的touch元素 touch_element = WebDriverWait(self, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'ipc-starbar__touch')) ) self.execute_script("arguments[0].style.display = 'none';", touch_element) # 再点击目标评分按钮 target_rate_btn.click()
内容的提问来源于stack exchange,提问作者mohammad
相关产品推荐
相关产品推荐

