[英]printing an output of javascript in a webpage using selenium and python
I was making an python program that executes a java script after loading a webpage it is a web based api where we can execute javascript commands through console of your browser (f12) ( api documentation ) 我正在制作一个python程序,该程序在加载网页后执行Java脚本,它是基于Web的api,我们可以在其中通过浏览器的控制台(f12)执行javascript命令(api 文档 )
This executing gives back an array, I just want to get this output of execution (the array) to be print. 这个执行返回一个数组,我只想获取执行的输出(数组)以进行打印。 the code i used is given below.
我使用的代码如下。 the time delay of 15 seconds is used for solving an captcha which have to do manually.
15秒的延迟时间用于解决必须手动执行的验证码。 executing
getPlayerList();
执行
getPlayerList();
command will give back you a list of players that is currently playing. 命令将返回给您当前正在播放的玩家列表。
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();
"""))
The above program works fine, but i have to print the output of getPlayerList();
上面的程序工作正常,但是我必须打印
getPlayerList();
的输出getPlayerList();
I tried with return
and console log
, but that is not working for me. 我尝试使用
return
和console log
,但这对我不起作用。
you need to define your getPlayerList()
function take this as example: 您需要以以下示例定义
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();
""")
I am Agree with the @zimdero answer and the @GalAbra comment if you use Selenium. 如果您使用Selenium,我同意@zimdero答案和@GalAbra注释。
But if you have absolutely the requirement to execute the javascript function which is present in the loaded page , you may achieve this by use of PyQt and QwebView class, with something like this: 但是, 如果绝对需要执行已加载页面中存在的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()"))
For more information, take a look on How to call javascript function from PyQT 有关更多信息,请查看如何从PyQT调用javascript函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.