如何切换到 inside another s in selenium

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

我试图点击嵌套DIV内的按钮。下面是html

<div class="chat-message-container ngi bot" chat-msg-id="EzPtItD3exi2lTGS3SQkV0-h|0000016" chat-msg-text="What is the intended purpose of your investment">
            <div class="message-bubble">

                <div class="message-text"><p>What is the intended purpose of your investment</p>
                </div>
                >
            </div>
            <div class="attachment-container">
        <div id="0attachment" style="display: block" class="attachment">
            <div class="attachment-info">
                <div class="attachment-title"></div>
                <p class="attachment-subtitle-1"></p>
                <p class="attachment-subtitle-2"></p>
                <div class="carousel-counter-container">
                    <button type="button" id="0prev" class="carousel-btn-ngi" data-atura-carousel="prev">&lt;</button>
                    <p class="carousel-counter" }"="">1/1</p>
                    <button type="button" id="0next" class="carousel-btn-ngi" data-atura-carousel="next">&gt;</button>
                </div>
            </div>

            <div class="action-button-container"><a href="0 - 3 years" class="link-as-button quick-reply" data-instant-message-reply-ngi="" data-button-display-value="0 - 3 years">0 - 3 years</a><a href="3 - 5 years" class="link-as-button quick-reply" data-instant-message-reply-ngi="" data-button-display-value="3 - 5 years">3 - 5 years</a><a href="over 5 years" class="link-as-button quick-reply" data-instant-message-reply-ngi="" data-button-display-value="over 5 years">over 5 years</a>
            </div>
        </div></div>
        </div>

我需要点击按钮0 - 3年

我试图使用xpath单击元素,如下所示:driver.findElement(By.xpath(“// * [@ id ='0 attachment'] / div [2] / a [1]”))。click();

那没起效。我认为这是因为嵌套结构。我读到了切换方法。但我不认为可以用来切换另一个DIV

请帮助

selenium selenium-webdriver
1个回答
1
投票

对于带有文本0到3年的元素的click(),需要引导WebDriverWait以使所需元素可单击,并且您可以使用以下任一解决方案:

  • 使用LINK_TEXTWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "0 - 3 years"))).click()
  • 使用PARTIAL_LINK_TEXTWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "0 - 3 years"))).click()
  • 使用CSS_SELECTORWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.action-button-container>a.link-as-button.quick-reply[data-button-display-value='0 - 3 years']"))).click()
  • 使用XPATHWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='action-button-container']/a[@class='link-as-button quick-reply' and contains(., '0 - 3 years')]"))).click()
  • 注意:您必须添加以下导入: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
© www.soinside.com 2019 - 2024. All rights reserved.