SFro SFro - 13 days ago 5
Python Question

Clicking button within span with no ID using Selenium

I'm trying to have click a button in the browser with Selenium and Python.

The button is within the following

<div id="generate">
<i class="fa fa-bolt"></i>
<span>Download Slides</span>
<div class="clear"></div>
</div>


Chrome's dev console tells me the button is within
<span>
but I have no idea how to reference the button for a
.click()
.

Answer

Well, if you just want to click on an element without an id or name, I'd suggest three ways to do it:

  1. use xpath:

    driver.find_element_by_xpath('//*[@id="generate"]/span')
    
  2. use CSS selector:

    driver.find_element_by_css_selector('#generate > span')
    
  3. Just try .find_element_by_tag_name() like:

    driver.find_element_by_id('generate').find_elements_by_tag_name('span')[0]
    

    Note that this way first try to get the generate <div> element by it's id, and then finds all the <span> elements under that <div>.

    Finally, gets the first <span> element use [0].