第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PyQt5加載網頁內容時返回None值

PyQt5加載網頁內容時返回None值

慕的地8271018 2023-08-15 18:44:54
我正在嘗試獲取網頁部分的內容。該部分中的數據由 JavaScript 動態(tài)加載。我在這里找到了一些代碼,對其進行了編輯,但是當我運行腳本時我返回None這是代碼import bs4 as bsimport sysimport urllib.requestfrom PyQt5.QtWebEngineWidgets import QWebEnginePagefrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtCore import QUrlfrom pprint import pprintclass Page(QWebEnginePage):    def __init__(self, url):        self.app = QApplication(sys.argv)        QWebEnginePage.__init__(self)        self.html = ''        self.loadFinished.connect(self._on_load_finished)        self.load(QUrl(url))        self.app.exec_()            def _on_load_finished(self):        self.html = self.toHtml(self.Callable)        print('Load finished')    def Callable(self, html_str):        self.html = html_str        self.app.quit()def main():    page = Page('https://www.ibm.com/support/fixcentral/swg/selectFixes?parent=IBM%20Security&product=ibm/Information+Management/InfoSphere+Guardium&release=10.0&platform=Linux&function=all')    soup = bs.BeautifulSoup(page.html, 'html.parser')    section = soup.find('table', {'id' : 'DataTables_Table_0'})    pprint (section)if __name__ == '__main__': main()這是輸出Load finishedNone
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

loadFinished 信號僅指示頁面已加載,但之后可以創(chuàng)建更多 DOM 元素,這就是 id 為“DataTables_Table_0”的元素的情況,該元素是在頁面加載后立即創(chuàng)建的。


一個可能的解決方案是注入一個腳本來檢查該元素是否存在,并發(fā)出通知以便獲取 HTML。


import sys

from functools import cached_property


from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel


from pprint import pprint

import bs4 as bs



def get_webchannel_source():

    file = QtCore.QFile(":/qtwebchannel/qwebchannel.js")

    if not file.open(QtCore.QIODevice.ReadOnly):

        return ""

    content = file.readAll()

    file.close()

    return content.data().decode()



class Manager(QtCore.QObject):

    def __init__(self, *, offline=True, visible=False, parent=None):

        super().__init__(parent)

        self._html = ""

        self._is_finished = False

        self.app

        self._profile = (

            QtWebEngineWidgets.QWebEngineProfile()

            if offline

            else QtWebEngineWidgets.QWebEngineProfile.defaultProfile()

        )

        self.view.resize(640, 480)

        if not visible:

            self.view.setAttribute(QtCore.Qt.WA_DontShowOnScreen, True)

        self.view.show()

        self.webchannel.registerObject("manager", self)

        self.view.page().setWebChannel(self.webchannel)


    @cached_property

    def app(self):

        return QtWidgets.QApplication(sys.argv)


    @property

    def profile(self):

        return self._profile


    @cached_property

    def view(self):

        view = QtWebEngineWidgets.QWebEngineView()

        page = QtWebEngineWidgets.QWebEnginePage(self.profile, self)

        view.setPage(page)

        return view


    @cached_property

    def webchannel(self):

        return QtWebChannel.QWebChannel(self)


    @property

    def html(self):

        return self._html


    def set_script(self, script):

        qscript = QtWebEngineWidgets.QWebEngineScript()

        qscript.setName("qscript")

        qscript.setSourceCode(get_webchannel_source() + "\n" + script)

        qscript.setInjectionPoint(QtWebEngineWidgets.QWebEngineScript.DocumentReady)

        qscript.setWorldId(QtWebEngineWidgets.QWebEngineScript.MainWorld)

        self.profile.scripts().insert(qscript)


    def start(self, url):

        self.view.load(QtCore.QUrl.fromUserInput(url))

        self.app.exec_()


    @QtCore.pyqtSlot()

    def save_html(self):

        if not self._is_finished:

            self.view.page().toHtml(self.html_callable)

            self._is_finished = True


    def html_callable(self, html):

        self._html = html

        self.app.quit()



JS = """

var manager = null;


function find_element() {

  var e = document.getElementById('DataTables_Table_0');

  console.log("try verify", e, manager);

  if (e != null && manager != null) {

    console.log(e)

    manager.save_html()

  } else {

    setTimeout(find_element, 100);

  }

}


(function wait_qt() {

  if (typeof qt != 'undefined') {

    console.log("Qt loaded");

    new QWebChannel(qt.webChannelTransport, function (channel) {

      manager = channel.objects.manager;

      find_element();

    });

  } else {

    setTimeout(wait_qt, 100);

  }

})();

"""



def main():

    manager = Manager()

    manager.set_script(JS)

    manager.start(

        "https://www.ibm.com/support/fixcentral/swg/selectFixes?parent=IBM%20Security&product=ibm/Information+Management/InfoSphere+Guardium&release=10.0&platform=Linux&function=all"

    )

    soup = bs.BeautifulSoup(manager.html, "html.parser")

    section = soup.find("table", {"id": "DataTables_Table_0"})

    pprint(section)



if __name__ == "__main__":

    main()



查看完整回答
反對 回復 2023-08-15
  • 1 回答
  • 0 關注
  • 209 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號