通过selenium动态创建新元素

2024-04-19 09:52:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要的是在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)

Tags: text文档脚本returnhtmldriverscriptfunction
1条回答
网友
1楼 · 发布于 2024-04-19 09:52:34

当然,您可以通过seleniumexecute_scriptapi将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的控制台选项卡中逐个执行以下4行:

enter image description here

如果您可以得到一个警告,在HTML head中插入一个script标记,这意味着javascript片段在您的浏览中运行良好,失败应该来自于其他python代码行

enter image description here

相关问题 更多 >