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

时间:2018-02-19 07:08:01

标签: python selenium web-scraping

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

1 个答案:

答案 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行:

enter image description here

如果您可以在HTML script中获得警告,插入head标记,则表示javascript代码段在您的浏览中正常工作,失败应来自其他python代码行

enter image description here