首页 > 解决方案 > 如何切换到

在另一个里面
硒中的 s

问题描述

我正在尝试单击嵌套 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='0attachment']/div[2]/a[1]")).click();

它不起作用。我认为这是因为嵌套结构。我读到了 switch 方法。但我认为这不能用于在另一个 DIV 内切换

请帮助

标签: seleniumselenium-webdriver

解决方案


click()在文本为0 - 3 年的元素上引入WebDriverWait以使所需元素可点击,您可以使用以下任一解决方案:

  • 使用LINK_TEXT

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "0 - 3 years"))).click()
    
  • 使用PARTIAL_LINK_TEXT

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "0 - 3 years"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(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()
    
  • 使用XPATH

    WebDriverWait(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
    

推荐阅读