Reputation: 2434
I am creating a bot with Selenium Python. I am trying to click on an element that is not visible (only visible after clicking on a button to expand a tree), so I am using JavaScript to execute a script like this:
entity_ID = '1200'
js = """document.querySelector("div[data-id='{0}']").click()""".format(entity_ID)
driver.execute_script(js)
This returns JavascriptException: Message: javascript error: Cannot read property 'click' of null
. If I expand the tree so the element is visible, the above code runs successfully. If I collapse the tree so the element is no longer visible...the above code runs successfully. Why does this work only when the element is visible or has been visible in the past?
The element (within the tree) looks like this:
<div class="rowContainer js-tree-row AssessmentTreeGrid unselectable ui-selected treegridinlineedit" data-id="1200" data-type="15005" data-bid="0" data-role="1" data-key="false" data-testresult="0" data-strategic="false" data-released="false" data-mtallowedactions="12600,11800,8700,12000,8100,32200,32400,5400,26300,26400,32600,32500,32100,19500" data-mtunallowedactions="" data-mtunallowedactionreasons="" data-uiallowedactions="500,600" data-allowedreorder="false" data-collapsible="true" tabindex="0" unselectable="on">
The full traceback looks like this:
JavascriptException Traceback (most recent call last)
<ipython-input-332-7945dcef4da6> in <module>
----> 1 driver.execute_script(js)
~\AppData\Local\conda\conda\envs\robotics\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute_script(self, script, *args)
634 return self.execute(command, {
635 'script': script,
--> 636 'args': converted_args})['value']
637
638 def execute_async_script(self, script, *args):
~\AppData\Local\conda\conda\envs\robotics\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)
319 response = self.command_executor.execute(driver_command, params)
320 if response:
--> 321 self.error_handler.check_response(response)
322 response['value'] = self._unwrap_value(
323 response.get('value', None))
~\AppData\Local\conda\conda\envs\robotics\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)
240 alert_text = value['alert'].get('text')
241 raise exception_class(message, screen, stacktrace, alert_text)
--> 242 raise exception_class(message, screen, stacktrace)
243
244 def _value_or_default(self, obj, key, default):
JavascriptException: Message: javascript error: Cannot read property 'click' of null
(Session info: chrome=78.0.3904.97)
Upvotes: 0
Views: 4297
Reputation: 176
Try to run the test till the click, run in browser's console:
document.querySelector("div[data-id='<ID>']")
If you see 'null' then:
Upvotes: 1