简体   繁体   English

是否可以打开一个网站,然后使用 Python 在其中运行 JavaScript?

[英]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.我一直在尝试打开一个网站(使用 python),然后在其上运行 JavaScript 脚本。

I did the open the website part, but I haven't managed to get the JavaScript to run after the page loads.我做了打开网站部分,但我没有设法让 JavaScript 在页面加载后运行。

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.它会打开网站,但不会运行 javascript。

I used os.system() because other methods have problems with chrome.我使用os.system()是因为其他方法对 chrome 有问题。

I figured it out:我想到了:

VBScript and batch together to open the site then enter keystrokes VBScript 和批处理一起打开网站然后输入击键

' 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 ' https://www.codegrepper.com/code-examples/whatever/Make+a+batch+file+that+opens+site+in+browser+and+enter+login+information '对于开发这个答案非常有用

'''
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 .写完这篇文章后,我意识到import pynput是一种不涉及os.system的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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