在Python测试中使用Selenium按ID获取元素
在我下面的html代码中:
<div class="collapse navbar-collapse" id="b-menu-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="/accounts/login/">Sign In</a></li>
<li><a href="/accounts/signup/">Sign Up</a></li>
{% if request.user.is_authenticated or logged_in %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-user"></span><b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/accounts/manageAccount/">Manage Account</a></li>
<li><a href="/accounts/createProfile/">create profile</a></li>
<li><a href="/accounts/viewProfile/">view profile</a></li>
<li><a href="/accounts/editProfile/">edit profile</a></li>
<li><a href="/accounts/logout/" id="logout">Log out</a></li>
</ul>
</li>
<li data-toggle="modal" data-target="#my-modal-box" class="active">
<a href="#"><span class="glyphicon glyphicon-search"> Search</a></li>
</ul>
</div>
我想选择登出按钮,它实际上出现在我的导航栏的一个选择器中。
我尝试通过名称、ID等方式获取这个元素,但都没有成功。
elem2 = self.driver.find_element_by_id("logout")
elem2.send_keys(Keys.RETURN)
我在登出的链接中明确添加了ID,但还是无法抓取到这个元素。有什么建议可以让我获取到登出元素吗?
我遇到了下面的异常:
NoSuchElementException: Message: u'Unable to locate element: {"method":"id","selector":"logout"}' ; Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmpPHM5S7/extensions/fxdriver@googlecode.com/components/driver_component.js:8905)
at FirefoxDriver.prototype.findElement (file:///tmp/tmpPHM5S7/extensions/fxdriver@googlecode.com/components/driver_component.js:8914)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpPHM5S7/extensions/fxdriver@googlecode.com/components/command_processor.js:10884)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpPHM5S7/extensions/fxdriver@googlecode.com/components/command_processor.js:10889)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpPHM5S7/extensions/fxdriver@googlecode.com/components/command_processor.js:10831)
2 个回答
0
这个内容来自于 Selenium / Firefox: 命令 ".click()" 对找到的元素不起作用
def javascript_manual_click(driver, element_id):
we = driver.find_element_by_id(element_id)
driver.execute_script("arguments[0].click();", we)
javascript_manual_click("logout")
0
你有没有试过使用UI支持中的Select(类selenium.webdriver.support.select.Select(webelement))?
我对Python不太了解,所以我的例子是用Java写的:
WebElement dropDownMenu = webDriver.findElement(By.xpath("//ul[@class='dropdown-menu']");
Select logout = new Select(dropDownMenu);
logout.selectByVisibleText("Log out");