gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:58:34 24 4
gpt4 key购买 nike

我有一个代码,单击网页上的按钮,会弹出一个菜单栏。我想从出现的选项中选择一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com