0

I want to click an element with javascript throught a selenium driver with Python, this is an example of my code:

driver.execute_script("els=document.getElementsByClassName('buttons');\
    for (var i = 0; i < els.length; i++) {\
        open=els[i].parentNode.getElementsByClassName('button_open');\
        if(open.length==1){\
            alert('ok');\
        }else(\
            alert('not ok')\
            els[i].click();\
        )\
    }")

and the html code:

<div class="buttonsParent">
    <div class="buttons button_open">
        <span>Content</span>
    </div>
</div>
<div class="buttonsParent">
    <div class="buttons">
        <span>Content</span>
    </div>
</div>
Teodoros
  • 459
  • 4
  • 14
  • what is the error you getting? why this code is not clicking on element? – Dev Sep 21 '19 at 20:41
  • There are no errors into the console, but if i remove els[i].click();, then the alert is working, otherwise not – Teodoros Sep 21 '19 at 21:12

1 Answers1

0

Webdriver and Selenium can be a bit finicky at times. Try clicking using xpath, it has been the most successful for me. Inspect element, right click on copy, and copy xpath button.

Some sample code would look like:

website = 'url here'
driver = webdriver.Chrome()
driver.get(website)

variable = driver.find_element_by_xpath('xpath here')
driver.find_element_by_xpath('xpath here').click()

Side note: make sure there are no pop-ups or other buttons that could interrupt the automatic button press. I have experienced in the past where my program would stop because the button could not be found due to another element being in the webdriver screen or blocking the button I wanted to press.

This might help as it deals with javascript directly.

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

Entroyp
  • 61
  • 1
  • 9