简体   繁体   中英

What is the correct way to run execute_script with selenium Python?

I want to automatically log in to Discord using a JS code that needs to be pasted into the browser console. I'm just learning Python and have absolutely no knowledge of JS. Here is the code to paste into the console:

function login(token) {
    setInterval(() => {
      document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`
    }, 50);
    setTimeout(() => {
      location.reload();
    }, 2500);
  }

login(token);

Here is my failed attempt:

token = 'token'
driver.execute_script('return function login(token) {setInterval(() => {document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`}, 50);setTimeout(() => {location.reload();}, 2500);}login('+"'"+f'{token}'+"');")

Received an error:

selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected identifier 'login'
token = 'token'

js = 'function login(token) {setInterval(() => {document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`}, 50);setTimeout(() => {location.reload();}, 500);}'
time.sleep(3)
driver.execute_script(js + f'login("{token}")')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM