无法在selenium python中单击具有链接的元素

2024-04-26 13:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图与注销按钮交互,但似乎无法使用链接文本或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下的第一行调用一个函数,该函数等待某个元素出现在网页上,这样我就可以看到页面已经加载。然后我尝试单击“注销”按钮。在

这是HTML(元素位于^{cl1}$ ^{pr2}$

当我尝试通过link_文本查找时,找不到元素。运行此代码时会出现stacktrace错误:

ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with

编辑:我尝试过Saifur的答案,并将代码更新为他的答案,但现在我得到了:AttributeError:'BasicTestCase'对象没有属性'find\u element'。我试着把“自我”改成self.browser浏览器“作为WebDriverWait()中的一个参数,但是我会得到原始错误。在


Tags: 答案代码from文本importself元素selenium
2条回答

你需要一个明确的等待。See docs。示例代码:

element = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH,'//a[@href="/login/clear"]')))

然后单击元素。在

^{pr2}$

注意我在测试中添加了答案b/c,至少您不需要担心italics标记。那是文本,不是按钮,你也没有点击文本。因此,找到By.XPATH并选择一个唯一的属性(即,本例中的href,而不是class属性),然后单击元素。在

编辑:

请试试这一行:

element = WebDriverWait(self.browser, 30).until(EC.visibility_of_element_located((By.XPATH,'//a[@class="btn" and @href="/login/clear"]')))

使用explicit wait和相对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")

相关问题 更多 >