【问题标题】:Selenium (python) to select an item in dropdown menuSelenium(python)在下拉菜单中选择一个项目
【发布时间】:2022-01-23 07:48:15
【问题描述】:

我正在尝试在 python 中使用 Selenium 在以下下拉菜单中选择“自定义日期”项:

div 的结构如下所示:

我尝试首先使用 Selenium (python) 选择最顶部的 div,然后通过单击一直向下移动到“自定义日期”(参见下面的代码)。但是,当我尝试这样做时,在最后一行代码中出现以下错误:

"ElementNotInteractableException: Message: element not interactable"

我尝试点击所需的字段:

time.sleep(2)
element=chrome.find_element_by_xpath("//div[@class='Inputreact__StyledContainer-sc-3dr67n-0 iAeYiQ Selectreact__SelectInput-sc-1shssly-0 cJLIjY' ]")
element.click()
chrome.execute_script("arguments[0].click();", element)
element=chrome.find_element_by_xpath("//input[@value='7 days']")
chrome.execute_script("arguments[0].click();", element)
element=chrome.find_element_by_xpath("//input[@value='Custom date']")
chrome.execute_script("arguments[0].click();", element)

编辑: 我想提供更多细节。在用户手动使用下拉菜单的情况下,会发生以下行为(注意图片中的相关 div 是什么)。我被难住了,因为 selenium 单击以 ePfTsZ 结尾的 div 不会扩展下拉菜单,就像用户在浏览器中手动操作时那样。

【问题讨论】:

  • 当我在浏览器中手动单击下拉菜单以展开它时,aria-expanded 值从 false 变为 true。但是,无论出于何种原因,在我的代码中第一次单击后,selenium 似乎都无法访问“自定义日期”菜单字段。
  • 它在哪个网站上?
  • 还要通过 div 下拉菜单,您只需单击顶部 div 一次,然后单击您想要的值,否则下拉菜单将关闭。
  • 谢谢,但是,我只是尝试使用下面的代码实现您的建议(单击顶部 div 一次,然后单击您的值),我得到了同样的错误:
  • chrome.find_element_by_xpath("//div[@class='Blockreact__Block-sc-1xf18x6-0 ePfTsZ' ]").click() time.sleep(2) element=chrome.find_element_by_xpath(" //input[@value='自定义日期']") chrome.execute_script("arguments[0].click();", element)

标签: javascript python html css selenium


【解决方案1】:

在这种情况下,您需要使用 Select 类,看起来像这样:

from selenium.webdriver.support.select import Select

selection = Select(chrome.find_element_by_xpath(
    "//div[@class='Inputreact__StyledContainer-sc-3dr67n-0 iAeYiQ Selectreact__SelectInput-sc-1shssly-0 cJLIjY' ]"))

在此之后,您可以按索引或可见文本选择下拉列表中的任何项目。

selection.select_by_index(1)

或

selection.select_by_visible_text("A month")

【讨论】:

  • 谢谢。但是,我只是尝试这样做并收到以下错误: UnexpectedTagNameException: Message: Select only works on
【解决方案2】:

如果您想浏览下拉菜单的所有选项,请在索引上运行一个循环。

【讨论】:

  • 您能详细说明一下吗?例如,我将如何遍历所有选项,然后在索引上运行循环?
  • 属性area-invalid 具有布尔值。只有单击它才能看到它的完整属性。硒仅适用于可见属性。 (之前没有注意到这个值)。在这种情况下,您可以使用pyautogui。使用 api 与您的浏览器 UI 进行交互。
猜你喜欢
  • 2018-02-17
  • 2020-05-14
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2022-11-11
  • 1970-01-01
  • 2017-03-23
相关资源
最近更新 更多