如何使Python,QT和Webkit在无头服务器上工作? [英] How do I make Python, QT, and Webkit work on a headless server?

查看:84
本文介绍了如何使Python,QT和Webkit在无头服务器上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于各种用途的Debian Linux服务器.我希望它能够执行一些我需要定期进行的网络抓取工作.

I have Debian Linux server that I use for a variety of things. I want it to be able to do some web-scraping jobs I need done regularly.

可以在此处找到此代码.

import sys  
from PyQt4.QtGui import *  
from PyQt4.QtCore import *  
from PyQt4.QtWebKit import *  

class Render(QWebPage):  
  def __init__(self, url):  
    self.app = QApplication(sys.argv, False)  # Line updated based on mata's answer
    QWebPage.__init__(self)  
    self.loadFinished.connect(self._loadFinished)  
    self.mainFrame().load(QUrl(url))  
    self.app.exec_()  

  def _loadFinished(self, result):  
    self.frame = self.mainFrame()  
    self.app.quit()  

一个简单的测试看起来像这样:

A simple test of it would look like this:

url = 'http://example.com'
print Render(url).frame.toHtml()

在调用构造函数时,它会死于此消息(它被打印到stdout,而不是未捕获的异常).

On the call to the constructor it dies with this message (it's printed to stdout, not an uncaught exception).

: cannot connect to X server 

如何在无头服务器上使用Python(2.7),QT4和Webkit?不需要显示任何内容,因此我可以将任何设置或任何需要调整的时间调整为一周.

How can I use Python (2.7), QT4, and Webkit on a headless server? Nothing ever needs to be displayed, so I can tweek any settings or anything that need to be tweeked.

我已经研究了替代方案,但这对我和我的项目是最合适的.如果确实必须安装X服务器,该如何以最小的开销做到呢?

I've looked into alternatives, but this is the best fit for me and my projects. If I did have to install an X server, how could I do it with minimal overhead?

推荐答案

QApplication的构造函数之一采用布尔参数

One of the constructors of QApplication takes a boolean argument GUIenabled.
If you use that, you can instantiante QAppliaction without an X server, but you can't create QWidgets.

因此,在这种情况下,唯一的选择是使用虚拟X服务器,例如 Xvfb 呈现GUI.

So in this case the only option is to use a virtual X server like Xvfb to render the GUI.

可以使用以下命令安装和运行Xvfb(假设您已安装apt-get).原始问题中的代码在名为render.py的文件中.

Xvfb can be installed and run using these commands (assuming you have apt-get installed). The code in the original question is in a file called render.py.

sudo apt-get install xvfb
xvfb-run python render.py

这篇关于如何使Python,QT和Webkit在无头服务器上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆