我正在尝试与注销按钮交互,但我似乎无法使用链接文本或 xpath 单击它。
我尝试遵循这些答案,但没有成功:
这是我的代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from xatu.tests.base import login
from xatu.tests.bagon import BagonBaseTestCase
class BasicTestCase(BagonBaseTestCase):
@login
def test_logout(self):
self._wait_until_id_presents("quotes-form")
WebDriverWait(self, 10).until(
EC.presence_of_element_located((By.XPATH, "//a[@href='/login/clear']/i")))
self.browser.find_element_by_xpath("//a[@href='/login/clear']/i").click()
self.implicitly_wait(2)
self._title_check("Login")
test_logout 下的第一行调用一个函数,该函数等待某个元素出现在网页上,以便我可以看到该页面已加载。然后我尝试单击退出按钮。
这是 HTML(元素位于 class="btn"href="/login/clear"):
<div class="navbar navbar-fixed-top screen-only">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-target=".nav-collapse" data-toggle="collapse">
<a class="brand" href="/">
<div class="nav-collapse collapse">
<ul class="nav">
<p class="pull-right" style="margin-top: 4px; margin-left: 4px;">
<a class="btn" href="/login/clear">
<i class="icon-off"/>
Sign out
</a>
</p>
<p class="navbar-text pull-right"> Logged-in as D. V. Lauper </p>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
当我尝试通过 link_text 查找时,找不到该元素。运行此代码会出现堆栈跟踪错误:
ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
编辑:我已经尝试过 Saifur 的答案并将我的代码更新为他的答案,但现在我得到: AttributeError:“BasicTestCase”对象没有属性“find_element”。我尝试将“self”更改为“self.browser”作为 WebDriverWait() 中的参数,但随后我会得到原来的错误。
最佳答案
使用显式等待
和相对xpath
像//a[@href='/login/clear']/i
from xatu.tests.base import login
from xatu.tests.bagon import BagonBaseTestCase
class BasicTestCase(BagonBaseTestCase):
@login
def test_logout(self):
self._wait_until_id_presents("quotes-form")
WebDriverWait(self, 10).until(
EC.presence_of_element_located((By.XPATH, "//a[@href='/login/clear']/i")))
self.browser.find_element_by_xpath("//a[@href='/login/clear']/i").click()
self.browser.implicitly_wait(2)
self._title_check("Login")
关于python - 无法点击 selenium python 中带有链接的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867677/