我正在制作一个python程序,在加载webpage之后执行java脚本它是一个基于web的api,我们可以通过浏览器的控制台执行javascript命令(f12)(api documentation)
这个执行返回一个数组,我只想让这个执行输出(数组)打印出来。我使用的代码如下。 15秒的时间延迟用于解决必须手动执行的验证码。
执行getPlayerList();
命令将返回一个当前正在播放的玩家列表。
from selenium import webdriver
import time
import os
driver=webdriver.Firefox()
driver.get("https://html5.haxball.com/headless")
time.sleep(5)
driver.execute_script("""
window.room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });
""")
#the time dalay is to solve the captcha manually that appear on the browser after executing above javascript.
time.sleep(15)
print(driver.execute_script("""
console.log(window.getPlayerList();
"""))
上述程序运行正常,但是我必须打印getPlayerList();
的{{1}}输出return
和console log
,但这对我不起作用。
答案 0 :(得分:1)
您需要定义getPlayerList()
函数,以此为例:
from selenium import webdriver
driver=webdriver.Firefox()
driver.get("https://html5.haxball.com/headless")
driver.execute_script("""
// window.room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });
// define the getPlayerList() functio;
window.getPlayerList = function() {
// here you make all the functional that you need
return 'All players list';
}
""")
driver.execute_script("""
// now that we define our function, we can call it
console.log(window.getPlayerList();
""")
答案 1 :(得分:0)
如果您使用Selenium,我同意@zimdero答案和@GalAbra评论。
但如果您完全要求执行加载页面中的javascript函数,则可以通过使用PyQt 来实现此目的QwebView类,类似这样:
browser = QwebView()
browser.load(QUrl("https://html5.haxball.com/headless"))
frame = browser.page().currentFrame()
#do your stuff here
#execute js function inside the webpage
frame.evaluateJavaScript(QString("getPlayerList()"))