gpt4 book ai didi

python - 通过selenium动态创建一个新元素

转载 作者:太空宇宙 更新时间:2023-11-04 04:48:51 24 4
gpt4 key购买 nike

我需要的是在html文档的头部添加一个script标签。我正在使用下面的代码,但是当我查看页面源代码时,脚本不存在。提前谢谢你,

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 api 将 script 标签动态添加到 HEAD 中,请尝试下面的简单代码。如果有效,您可以将 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 的 Console Tab 中一一执行以下 4 行:

enter image description here

如果你能得到一个警告,一个在 HTML head 中插入的 script 标签,这意味着 javascript 片段在你的浏览器上工作正常,失败应该来自其他 python代码行

enter image description here

关于python - 通过selenium动态创建一个新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com