简体   繁体   中英

Would it be possible to open a website and then run JavaScript in it using Python?

I have been trying to open a website (using python), then run a JavaScript script on it.

I did the open the website part, but I haven't managed to get the JavaScript to run after the page loads.

import os
url='example.com'
jscode='alert(\'success\')'
os.system('start chrome.exe '+url+' javascript:'+jscode)

The code above is the best I can think of.

It opens the website but does not run the javascript.

I used os.system() because other methods have problems with chrome.

I figured it out:

VBScript and batch together to open the site then enter keystrokes

' https://www.codegrepper.com/code-examples/whatever/Make+a+batch+file+that+opens+site+in+browser+and+enter+login+information ' was very useful for developing this answer

'''
enclosed in '{}' means special characters

'~' or '{ENTER}' = [ENTER]
'^' = [CTRL]

multiple characters in the same list item are typed at the same time
'''

keyplan = ["^l","javascript:alert{(}'success'{)}","~"]

with open('temp.cmd','w') as f: pass
with open('temp.cmd', 'a') as f:
    #batch code section
    f.write(
     '@if (@CodeSection == @Batch) @then\n'
    +'@echo off\n'
    +'set SendKeys=CScript //nologo //E:JScript "%~F0"\n')
    +'START CHROME "example.com"\n'
    +'timeout /t 10\n'
    )#the timeout is to give time for the page to load
    
    #log keys in plan
    for key in keyplan:
        f.write('%SendKeys% "'+key+'"\n')
    
    f.write('goto :EOF\n')
    f.write('@end\n')
    
    #VBScript section
    f.write('var WshShell = WScript.CreateObject("WScript.Shell");\n')
    
    #send keys (runs on every '%SendKeys% "key")
    f.write('WshShell.SendKeys(WScript.Arguments(0));\n')
os.system("temp.cmd")

After writing this I have realized that import pynput is a method that would not involve os.system .

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