Python Selenium从 "menuitem"中选择 "menubar"

标签 python python-2.7 selenium selenium-webdriver menuitem

我有一个代码,单击网页上的按钮,会弹出一个菜单栏。我想从出现的选项中选择一个menuitem,然后单击menuitem(如果可能);然而,我遇到了障碍。

这是迄今为止代码的相关部分:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('URL')

Btn = driver.find_element_by_id('gwt-debug-BragBar-otherDropDown')
Btn.click()  #this works just fine

MenuItem = driver.find_element_by_id('gwt-uid-463')  #I'm stuck on this line
MenuItem.click()

根据我所写的内容,这是它抛出的错误:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element

注意:每次页面加载时,该元素的 id 都会发生变化(这可能是错误的原因)。我也尝试过通过 find_element_by_class_name 搜索元素,但它有一个复合类名,而且我也一直收到错误。

这是菜单栏的代码:

<div class="gux-combo gux-dropdown-c" role="menubar" id="gwt-debug-BragBar-otherMenu">

以及我想要的menuitem:

<div class="gux-combo-item gux-combo-item-has-child" id="gwt-uid-591" role="menuitem" aria-haspopup="true">text</div>

我正在寻找一种选择菜单项的方法。谢谢!

最佳答案

试试这个 xpath

driver.find_element_by_xpath('//div[@role='menuitem' and .='text']').click();

它将检查“div”元素是否具有属性“role”作为“menuitem”并且具有精确文本作为“text”。

假设您的菜单下有一个菜单项“Lamborghini AvenTaDor”。因此,其代码将变为:

driver.find_element_by_xpath('//div[@role='menuitem' and .='Lamborghini AvenTaDor']').click();

关于Python Selenium从 "menuitem"中选择 "menubar",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26813230/

相关文章:

python - 如何在Python3中使用exec根据字典将列表分配给变量?

python - 如何以纯数据格式获取 Python Sphinx 文档?

python - 为 matplotlib 图分配随机颜色

python - python3.5中无法导入Kicad的Pcbnew

python - selenium 是否写入和读取 webelement 值

java - WebDriver - 无法找到元素

python - osquery-python 扩展导致 osqueryi 错误

python - 音频流 Python 上的 Google 流式语音识别

python - 在二维列表中交换 0 和 1 的最快方法

jquery - 使用 Python/Selenium 从日期选择器中选择日期后提取格式化日期