【问题标题】:Why is Selenium unable to click a button from a list of buttons?为什么 Selenium 无法单击按钮列表中的按钮?
【发布时间】:2021-01-07 07:31:00
【问题描述】:

我正在尝试访问网页上的特定按钮,以便我可以单击它并抓取另一侧的内容。我正在尝试使用 Selenium 返回特定 div 下的按钮列表,以便我可以单击第一个。但是,我在单击第 0 个索引时收到错误消息。

我收到以下错误:

ElementNotInteractableException:消息:元素不可交互
(会话信息:chrome=87.0.4280.88)

如果元素在列表中,我是否无法单击它们?或者这可能是别的什么?

网页:https://profiles.ucr.edu/app/home

HTML 图片和所需的 ID 元素。我想点击红色的“浏览”按钮: div and button HTML

这是我正在使用的代码,但它返回一个错误。我注释掉了打印按钮列表的功能:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys    
import time


PATH = "C:\Program Files (x86)\chromedriver.exe"    #path to webdriver executable
wd = webdriver.Chrome(PATH)

urlDepartments = 'https://profiles.ucr.edu/app/home'

wd.get(urlDepartments)
time.sleep(1)

idFirst = 'cdk-accordion-child-'
idNum = 0
idNumStr = str(0)
div = wd.find_element_by_id(idFirst + idNumStr)
button = div.find_elements_by_tag_name('button')
button[0].click()
#print(button)

【问题讨论】:

  • 找到红色浏览按钮以在网页profiles.ucr.edu/app/home上可见的步骤是什么?
  • 没有提供足够的信息。这通常发生在元素被隐藏、禁用或被覆盖覆盖时。尝试等待(element_to_be_clickable)很有用,这可能会解决错误。更多信息:selenium.dev/selenium/docs/api/java/org/openqa/selenium/…
  • 我使用 "wd.find_element_by_id('cdk-accordion-child-0') 找到包含四个按钮的 div,其中第一个是我想要的。然后我使用了 div.find_elements_by_tag_name ('button') 找到该 div 标签的子按钮
  • 我会试试等待功能

标签: python html selenium web-scraping selenium-chromedriver


【解决方案1】:

您需要等待按钮变为可点击,或者它可能尚未显示在屏幕上,您可以尝试以下操作:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys    
import time


PATH = "C:\Program Files (x86)\chromedriver.exe"    #path to webdriver executable
wd = webdriver.Chrome(PATH)

urlDepartments = 'https://profiles.ucr.edu/app/home'

wd.get(urlDepartments)
time.sleep(1)

idFirst = 'cdk-accordion-child-'
idNum = 0
idNumStr = str(0)
div = wd.find_element_by_id(idFirst + idNumStr)
button = div.find_elements_by_tag_name('button')
print("Is visible: " + str(element_name.is_displayed()))
time.sleep(3)
button[0].click()
#print(button)

【讨论】:

  • 那么,即使 Selenium 可以检测到按钮,它也无法单击它,因为它无法“看到它”?类似于人类如何假设 StackOverflow 的登录按钮存在,因为他们的页面尚未完全加载,因此他们能够单击它?
  • 另外,我将变量 div 插入到 element_name 中,但我得到了同样的错误。将这个变量插入那里是预期的想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2022-06-11
  • 2020-07-30
相关资源
最近更新 更多