问题
What I need is to add a script tag to the head of html document. I am using the code below but when I view page source, the script is not there. Thank you in advance,
driver = webdriver.Chrome()
driver.get("http://www.x.org")
execu = '''
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.text = `let calls = (function(){
let calls = 0;
let fun = document.createElement;
document.createElement = function(){
calls++;
return fun.apply(document, arguments);
}
return ()=>calls;
})();`
document.head.appendChild(scr);
'''
try:
driver.execute_async_script(execu)
except Exception,e:
print str(e)
回答1:
Absolutely you can add script
tag into HEAD
dynamically by selenium execute_script
api, please try below simple code. if it work, you can change the scr.text
to your content
driver = webdriver.Chrome()
driver.get("http://www.x.org")
// sleep 10 seconds wait page load complete
// you should change to wait in official script
time.sleep(10)
execu = '''
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.text = 'alert("yes")';
document.head.appendChild(scr);
'''
try:
driver.execute_script(execu) // if it work, an alert with 'yes' should display
// sleep for a long time, so that you have more time to
// check the script tag appended into head tag or not.
// only for debug purpose
time.sleep(30)
except Exception,e:
print str(e)
Please execute below 4 lines one by one in DevTool's Console Tab:
If You can get an alert, an inserted script
tag in HTML head
, it means the javascript snippet worked fine on your browse, the failure should comes from other python code lines
来源:https://stackoverflow.com/questions/48861078/create-a-new-element-by-selenium-dynamically