簡體   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