Home > other >  Change css element style with Python Selenium
Change css element style with Python Selenium

Time:10-26

I want to change the css element style using Python Selenium while doing automation to increase the height of the page. The html of the element is as follows:

<div style="overflow-y:scroll;overflow-x:hidden;height:150px;">

I know that I can use something like the code below to do this:

driver.execute_script("document.getElementById('id name').style.height = '2000px';")

or

driver.execute_script("document.getElementByClassName('class name').style.height = '2000px';")

But there is no id or class in the HTML (there's only style).

CodePudding user response:

If no ID or class is present then please use CSS

driver.execute_script("document.getElementByCss('div[style='overflow-y:scroll']').style.height = '2000px';")

But you should check in HTML DOM for the mentioned CSS :

Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the CSS and see, if your desired element is getting highlighted with 1/1 matching node.

CSS you should check :

div[style='overflow-y:scroll']

or

div[style='overflow-y:scroll'][sytle$='height:150px;']

or

div[style='overflow-y:scroll;overflow-x:hidden;height:150px;']

Whichever has the unique entry put that in execute_script and you should be good to go after that.

Alternate way to do

element = driver.find_element_by_css_selector("div[style='overflow-y:scroll;overflow-x:hidden;height:150px;']")
driver.execute_script("arguments[0].setAttribute('style','overflow-y:scroll;overflow-x:hidden;height:2000px;')", element)
  • Related