问题
I'm trying to open an accordion link with selenium in python.
The element looks like this when closed:
<div class="crm-accordion-body" style="display: none;">
and this when open:
<div class="crm-accordion-body" style="display: block;">
The code I'm trying to use to change the style is:
driver.execute_script("document.getElementsByClassName('crm-accordion-body').style.display = 'block';")
This produces the following error:
WebDriverException: Message: unknown error: Cannot set property 'display' of undefined
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86_64)
Anyone know what I'm doing wrong?
Thanks.
回答1:
Basically, document.getElementsByClassName('crm-accordion-body')
returns a Node List. So we have to use index to get hold of the intended Node as follows :
document.getElementsByClassName('btn-pageMenu')[0].style.display
So as we are trying to change the style="display: none;"
for the first node, try the following line of code :
driver.execute_script("document.getElementsByClassName('crm-accordion-body')[0].style.display='block';")
来源:https://stackoverflow.com/questions/47115719/open-an-accordion-with-selenium-in-python