简体   繁体   中英

How do you click an expander button in Python with Selenium?

I am working on a script for selenium to open a webpage, and click a series of buttons. The first button is an Expander button, shown in the below image

展开按钮

The HTML code from inspecting the button is below, but the button itself is "class="dojoxExpandoIcon dojoxExpandoIconLeft qa-button-toc"

<div class="dojoExpandoPaneInner">
        <div data-dojo-attach-point="titleWrapper" class="dojoxExpandoTitle">
            <div class="dojoxExpandoContainer">
                <div class="dojoxExpandoIcon dojoxExpandoIconLeft qa-button-toc" data-dojo-attach-point="iconNode" data-dojo-attach-event="ondijitclick:_onIconNodeClick" tabindex="0" aria-controls="slideout"><span class="a11yNode">X</span></div>
            </div>

The xpath as well, is as follows:

/html[@class='dj_webkit dj_chrome dj_contentbox has-webkit has-no-quirks svg']/body[@class='claro original']/div[@id='border']/div[@id='slideout']/div[@class='dojoExpandoPaneInner']/div[@class='dojoxExpandoTitle']/div[@class='dojoxExpandoContainer']/div[@class='dojoxExpandoIcon dojoxExpandoIconLeft qa-button-toc']

To find this button, I tried the following code one at a time.

driver.find_element_by_css_selector("div[class^='dojoxExpandoIcon']")    # find expander by class name
# driver.find_element_by_css_selector("div[class^='dojoxExpandoIcon dojoxExpandoIconLeft qa-button-toc']")    # find expander by class name
# driver.find_element_by_css_selector("div.dojoxExpandoContainer")

However, none of them have worked at all, and result in errors such as

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"div.dojoxExpandoIcon.dojoxExpandoIconLeft.qa-button-toc"}

Is there anything I'm doing wrong here?

Try waiting until the locator is clickable:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".dojoxExpandoIcon.dojoxExpandoIconLeft.qa-button-toc")))
button = driver.find_element_by_css_selector(".dojoxExpandoIcon.dojoxExpandoIconLeft.qa-button-toc").click()

If the number of classes is not stable, remove the ones that are changing and leave only stable ones, for example:

.dojoxExpandoIconLeft.qa-button-toc

Here I just removed one of classes.

Read more about waits here https://selenium-python.readthedocs.io/waits.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM