Skip to main content
 首页 » 编程设计

python之无法单击 Selenium python中带有链接的元素

2024年10月25日10sky-heaven

我正在尝试与注销按钮交互,但我似乎无法使用链接文本或 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")