我现在正试图编写一些代码来从Java渲染的页面中爬取网络内容。我在网上找到了一些使用PyQt5的示例。然而,当我安装了PyQt5.5.7并尝试导入它的模块时(ImportError:无法导入名称'QWebPage'),失败了。以下是参考代码。非常感谢任何人可以提供解决此问题的建议或其他爬取Java渲染的网页内容的方法。
# standard imports
import sys
# third-party imports
import requests
from bs4 import BeautifulSoup
from pyvirtualdisplay import Display
from PyQt5.QtWebEngineWidgets import QWebPage
from PyQt5.QtWidgets import QApplication
class Render(QWebPage):
"""Render HTML with PyQt5 WebKit."""
def __init__(self, html):
self.html = None
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().setHtml(html)
self.app.exec_()
def _loadFinished(self, result):
self.html = self.mainFrame().toHtml()
self.app.quit()
url = 'https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages/'
# get the raw HTML
source_html = requests.get(url).text
# return the JavaScript rendered HTML
with Display(visible=0, size=(800, 600)):
rendered_html = Render(source_html).html
# get the BeautifulSoup
soup = BeautifulSoup(rendered_html, 'html.parser')
print('title is %r' % soup.select_one('title').text)