繁体   English   中英

使用Selenium和python在网页中打印javascript的输出

[英]printing an output of javascript in a webpage using selenium and python

我正在制作一个python程序,该程序在加载网页后执行Java脚本,它是基于Web的api,我们可以在其中通过浏览器的控制台(f12)执行javascript命令(api 文档
这个执行返回一个数组,我只想获取执行的输出(数组)以进行打印。 我使用的代码如下。 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();的输出getPlayerList(); 我尝试使用returnconsole log ,但这对我不起作用。

您需要以以下示例定义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();
""")

如果您使用Selenium,我同意@zimdero答案和@GalAbra注释。


但是, 如果绝对需要执行已加载页面中存在的javascript函数,则可以使用PyQtQwebView类来实现此目的 ,例如:

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()"))

有关更多信息,请查看如何从PyQT调用javascript函数

暂无
暂无

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

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