我需要的是在html文档的头部添加一个脚本标记。我正在使用下面的代码但是当我查看页面源代码时,脚本不存在。 提前谢谢你,
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)
答案 0 :(得分:0)
您绝对可以通过selenium script
api动态地将HEAD
标记添加到execute_script
,请尝试以下简单代码。如果有效,您可以将scr.text
更改为您的内容
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)
请在DevTool的控制台选项卡中逐一执行以下4行:
如果您可以在HTML script
中获得警告,插入head
标记,则表示javascript代码段在您的浏览中正常工作,失败应来自其他python代码行