-1

I have this on a website

div class="accept"  onclick="javascript:ClosePopup(true);" ...

If I run "ClosePopup(true)" in the browser console, the button works and closes the popup.

In selenium, I think something like driver.executeScript(ClosePopup(true)) but that is not the correct way. Please advice how to click the button once that is a popup that shows up only sometimes and do not have id, only a class but the class has 4 or more buttons inside.

I am using selenium with python 3.8.

CLpragmatics
  • 625
  • 6
  • 21
tiago calado
  • 156
  • 7

1 Answers1

1

In Python, there are a few components and methods to executing Javascript:

  1. Find the element you want to execute script on
  2. Pass in the element as a Javascript argument

This translates to:

# 1. find element
element = driver.find_element_by_xpath("//div[@class='accept']")

# 2. execute script
driver.execute_script("arguments[0].click();", element)

The Javascript function is reading in element as a parameter and performing .click() on the element. You do not have to pass in a WebElement, and you can use something like document.getElementById() in the Javascript function itself:

driver.execute_script("document.getElementById('id').click();")

Given the HTML for the div element you have provided, I don't think you actually need to use Javascript at all though. You should just be able to use:

driver.find_element_by_xpath("//div[@class='accept']").click()
CEH
  • 5,701
  • 2
  • 16
  • 40