How to Expand a List with Selenium Webdriver for Python

I am trying to expand a list with Selenium WebDriver for Python, which is controlled by a button that looks like this:

List When Closed

To give you an idea of how it looks when open:

List When Open

The HTML looks like this:

<div>  ##just for more information on the tree
<div>  ##
<ul>   ##

<li>
role = "presentation"
ng-if = "session.hasOccurrences" ## this is the name of a span
class = "expand-children ng-scope"

<button
role = "button"
class = "icon-button has tooltip" 
bb-translate-attrs = "{aria-label ': 'session.session-list.toggle-occurrences-aria'}"
aria-pressed = "false"
ng-click = "expand()"
aria-label = "Toggle session occurrences">
</button>

</li>

</ul>  ##
</div> ##
</div> ##

Since it had a tag name "button", I tried to use the following but it did not work:

url = 'Example.com'
driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_tag_name("button").click()

I tried to use xpath and CSS selectors, which I have very minimal experience with. Is there something I could do to expand the list?

Thank you for your help in advance.

2 answers

  • answered 2020-06-02 10:08 0buz

    Try an xpath like:

    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[@class='icon-button has tooltip']"))).click()
    

    This is based strictly on the html you have shared, in other words, assuming the xpath will match just one item on the page.

    Required imports:

    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    

  • answered 2020-06-02 10:49 Vemula Dheeraj

    Use 'contains method' in the XPath as mentioned below.

    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[contains(@class,'icon-button has tooltip')]"))).click()