如何在硒中另一个<div>内切换到<div>

时间:2019-04-28 18:10:26

标签: selenium selenium-webdriver

我试图单击嵌套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中切换

请帮助

1 个答案:

答案 0 :(得分:1)

要在文本为 0-3年的元素上click(),需要诱使 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