Create a new element by selenium dynamically

时光毁灭记忆、已成空白 提交于 2021-02-19 06:27:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!