to set MutationObserver, How to inject javascript before page-loading using Selenium

旧街凉风 提交于 2019-11-30 07:32:21

It's possible via the DevTool API by calling Page.addScriptToEvaluateOnNewDocument

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
import json

def send(driver, cmd, params={}):
  resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
  url = driver.command_executor._url + resource
  body = json.dumps({'cmd': cmd, 'params': params})
  response = driver.command_executor._request('POST', url, body)
  if response['status']:
    raise Exception(response.get('value'))
  return response.get('value')

def add_script(driver, script):
  send(driver, "Page.addScriptToEvaluateOnNewDocument", {"source": script})

WebDriver.add_script = add_script


# launch Chrome
driver = webdriver.Chrome()

# add a script which will be executed when the page starts loading
driver.add_script("""
  if (window.self === window.top) { // if main document
    console.log('add script');
  }
  """)

# load a page
driver.get("https://stackoverflow.com/questions")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!