Selenium“无法使用 LINK_TEXT 或 XPATH 定位元素”

问题描述 投票:0回答:1

我正在使用此代码...

class Browser:
    browser, service = None, None

    def __init__(self, driver:str):
        self.service = Service(driver)
        self.browser = webdriver.Edge() #webdriver.Edge(service=self.service)

    def open_page(self, url: str):
        self.browser.get(url)

    def close_browser(self):
        self.browser.close()

    def add_input(self, by: By, value: str, text: str):
        field = self.browser.find_element(by=by, value=value)
        field.send_keys(text)
        time.sleep(1)

    def click_button(self, by: By, value: str):
        button = self.browser.find_element(by=by, value=value)
        button.click()
        time.sleep(1)

    def login_kelio(self, user: str, password: str):
        self.add_input(by=By.ID, value="username", text=user)
        self.add_input(by=By.ID, value="password", text=password)
        self.click_button(by=By.XPATH, value='//input[@value="Confirm"]')
        self.click_button(by=By.XPATH, value='//div[@type="PortailVignetteLienExec"][1]')
        element = WebDriverWait(self.browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//*[contains(text(), "Consultar balance")]')))
        self.browser.execute_script("arguments[0].click();", element)

点击此按钮 -Consultar Balance-

<a class="boutonAction defaultActionBouton" href="javascript:void(0)" onclick="javascript:fcDoAction('AFFICHER__CD')">Consultar balance</a>

但是我总是在使用 XPATH 或 LINK_TEXT 时遇到错误

即:

“NoSuchElementException:消息:没有这样的元素:无法找到元素:”

这是元素的绝对路径:

/html/body/div#bwtcontainer/div/div/div/div/div/div/div/div/div/div/div/div/iframe/html/body/form#formAction/table#tableContenu/tbody/ tr/td/div.contenu/table/tbody/tr/td/div#badgeuseVirtuelleGTP/table/tbody/tr/td/fieldset/table/tbody/tr/td/a.boutonAction.defaultActionBouton

html python-3.x xml selenium-webdriver xpath
1个回答
0
投票

在单击按钮之前切换到 iframe 解决了问题,这就是我的做法。

iframe = self.browser.find_elements(By.TAG_NAME,'iframe')[0]
self.browser.switch_to.frame(iframe)
element = WebDriverWait(self.browser,5).until(EC.visibility_of_element_located((By.LINK_TEXT, 'Consultar balance')))
self.browser.execute_script("arguments[0].click();", element)

感谢@Shawn。

© www.soinside.com 2019 - 2024. All rights reserved.