Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

vba - How to perform multiline javascript instruction using Selenium Basic

I'm using VBA Selenium Basic to parse a HTML document, trying to change the attribute style from a td element. I tried to find methods like webelement.RemoveAtrr, webelement.SetAtrr or the like in vain.

After searching through DuckDuckGo and Stack Overflow, I came to think Selenium Basic can't remove, change or insert an attribute -- only read them. So I tried to do it using javascript.

Then I came to browser console and used the following lines:

var cell = document.querySelector('body > div > form:nth-child(5) > table > tbody > tr:nth-child(1) > tr:nth-child(1)');
cell.removeAttribute('class');
cell.setAttribute('style','background-color: #00FF7F;';

The javascript works fine on the page, discard old class information and adding new style information. So, I came to VBA and tried this:

oChrome.ExecuteScript "var sfCell = document.querySelector('body > div > form:nth-child(5) > table > tbody > tr:nth-child(1) > td:nth-child(1)');"
oChrome.ExecuteScript "sfCell.removeAttribute('class');"
oChrome.ExecuteScript "sfCell.setAttribute('style','background-color: #00FF7F;';"

But it didn't work. The first line runs but doesn't create the variable, as I can see in Console window. The second line retrieves an error from javascript, not from VB: sfCel.removeAttribute is not a function.

How should I perform javascript multiline instructions using ExecuteScript? I also accept ways to remove and change attributes not using javascript, but I'm honestly curious about the problem in the above code.

Thanks!

question from:https://stackoverflow.com/questions/65906513/how-to-perform-multiline-javascript-instruction-using-selenium-basic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to https://ui.vision/rpa/docs/selenium-ide/executescript

"The script fragment will be executed as the body of an anonymous function"

So perhaps your sfCell isn't making it to the global scope.

Try window.sfCell = ... to attach it to the global (window) scope.

Or alternatively omit the var and that should put the variable in the global scope - see Is using 'var' to declare variables optional?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...