【问题标题】:Python Selenium to select "menuitem" from "menubar"Python Selenium 从“menubar”中选择“menuitem”
【发布时间】:2014-11-08 02:52:23
【问题描述】:

我有一个代码可以点击网页上的一个按钮,它会弹出一个menubar。我想从出现的选项中选择menuitem,然后选择clickmenuitem(如果可能);但是,我遇到了障碍。

这里是到目前为止代码的相关部分:

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 搜索元素,但它有一个复合类名,我也一直在那儿出错。

这是menubar的代码:

<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>

我正在寻找一种方法来选择menuitem。谢谢!

【问题讨论】:

    标签: python python-2.7 selenium selenium-webdriver menuitem


    【解决方案1】:

    试试这个 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();
    

    【讨论】:

    • 这个想法+1,@Subh!这将真正帮助我在未来的编码工作中。
    【解决方案2】:

    您可以find the element by xpath 并检查id 属性gwt-uid- 开头

    menu_item = driver.find_element_by_xpath('//div[starts-with(@id, "gwt-uid-")]')
    menu_item.click()
    

    如果需要,您还可以应用其他检查,例如检查role 属性:

    driver.find_element_by_xpath('//div[starts-with(@id, "gwt-uid-") and @role="menuitem"]')
    

    【讨论】:

    • 感谢您的快速回答,@alecxe!试了一下,它完美地完成了这项工作。
    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 2012-01-19
    • 2022-09-23
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    相关资源
    最近更新 更多