Python Selenium定位Gurufocus页面100条股票显示按钮失败求助
解决Gurufocus股票页Selenium定位每页100条元素失败问题
问题重现
执行以下Selenium代码设置Gurufocus股票页面每页显示100条时,仅第一段点击下拉菜单的代码有效,第二段定位选择元素时抛出NoSuchElementException,使用find_element_by_id同样失败:
wd.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/section[2]/main/div/div[1]/div[3]/div[1]/span/div[2]").click() wd.find_element_by_xpath("/html/body/div[2]/div[6]").click()
报错信息:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='el-popover-2775']"} (Session info: chrome=106.0.5249.119)
解决方案
1. 替换动态/绝对定位方式
页面弹窗的ID(如el-popover-2775)是动态生成的,每次会话都会变化;绝对XPath也会因页面结构调整失效。改用基于文本或相对类名的定位:
# 直接定位显示"100"的选项 wd.find_element_by_xpath("//div[text()='100']").click() # 或更精准的相对路径(适配弹窗结构) wd.find_element_by_xpath("//div[contains(@class, 'el-popover')]//div[text()='100']").click()
2. 添加显式等待确保元素就绪
点击下拉菜单后,弹窗需要加载时间,直接定位会因元素未渲染完成报错。使用WebDriverWait等待元素可点击:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 点击下拉菜单 wd.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/section[2]/main/div/div[1]/div[3]/div[1]/span/div[2]").click() # 等待10秒,直到"100"选项可点击 WebDriverWait(wd, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[text()='100']")) ).click()
3. 排查是否存在iframe嵌套
如果弹窗被嵌套在iframe中,需先切换到iframe再操作元素:
# 定位弹窗所在的iframe(根据实际结构调整定位方式) iframe = wd.find_element_by_xpath("//iframe[contains(@class, 'popover-iframe')]") wd.switch_to.frame(iframe) # 等待并点击100选项 WebDriverWait(wd, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[text()='100']")) ).click() # 操作完成后切回主文档 wd.switch_to.default_content()
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

