【问题标题】:Create a new element by selenium dynamically通过 selenium 动态创建新元素
【发布时间】:2018-02-19 07:08:00
【问题描述】:

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

【问题讨论】:

  • 脚本不会添加到页面源。页面源是www.x.org返回的html。
  • 所以,你的意思是我不能通过 executescript() 将脚本添加到页面?

标签: python selenium web-scraping


【解决方案1】:

当然你可以通过 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 选项卡中一一执行以下 4 行:

如果您可以收到警报,在 HTML head 中插入 script 标记,这意味着 javascript sn-p 在您的浏览器上运行良好,故障应该来自其他 python 代码行

【讨论】:

  • 谢谢,但除了 time.sleep() 之外,您的代码与我的代码相同。它不起作用,我的意思是它似乎执行成功,但是当我查看页面源代码时,脚本不存在。
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 2015-03-04
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 2019-04-03
相关资源
最近更新 更多