通过 selenium 动态创建一个新元素 [英] Create a new element by selenium dynamically
问题描述
我需要的是在 html 文档的头部添加一个脚本标签.我正在使用下面的代码,但是当我查看页面源代码时,脚本不存在.预先感谢您,
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)
推荐答案
绝对可以通过 selenium execute_script
动态地将 script
标签添加到 HEAD
中api,请尝试下面的简单代码.如果可行,您可以将 scr.text
更改为您的内容
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)
请在 DevTool 的 Console Tab 中一一执行以下 4 行:
Please execute below 4 lines one by one in DevTool's Console Tab:
如果你能得到一个警告,在 HTML head
中插入一个 script
标签,这意味着 javascript 片段在你的浏览器上运行良好,失败应该来自其他 python代码行
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
这篇关于通过 selenium 动态创建一个新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!