Search code examples
javascriptpythonhtmlseleniuminnerhtml

Message: javascript error: Cannot set properties of null setting 'innerHTML' in Selenium 4.7.2 using Python


Tried to execute this script in selenium Python 4.7.2 with this line of code:

driver.execute_script('document.querySelector(".ck-placeholder").innerHTML = "TEST";')

I have checked DevTools, and the element does exist.

When running the code over this error appears:

selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot set properties of null (setting 'innerHTML')

I am trying to make a automatic messager bot that sends messages in Microsoft Teams via Selenium Python. I do know that there are other ways to send messages via apis, eg. but I want to learn Seleneium via this project.

The element: .ck-placeholder is the input field of Microsoft Teams (Messaging).

Here is the GitHub: https://github.com/LucasoDevDotTk/automatic_login_microsoft, send_msg.py is the file I'm working on

Expected results: innerHTML of .ck-placeholder to be replaced with "TEST"

Possible Causes: I havent checked if this is correct but .ck-placeholder is placed in an iframe, may this be the issue?

Picture of the iframe in devtools


Solution

  • The desired element is within an iframe so first you have to induce WebDriverWait for the frameToBeAvailableAndSwitchToIt as follows:

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.embedded-electron-webview.embedded-page-content")))
    driver.execute_script('document.querySelector(".ck-placeholder").innerHTML = "TEST";')
    

    Note : You have to add the following imports :

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