Python段错误,使用pyqt4

时间:2015-11-13 12:12:31

标签: python segmentation-fault beautifulsoup qt4 scrape

我写了一段代码来抓取一个实际使用它的网络,但是只要我在.txt中输入2个以上的ursl告诉我'分段错误'。我不知道问题出在哪里。任何帮助将不胜感激。

import sys
import time
import gc
from bs4 import BeautifulSoup
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import * 


class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        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.deleteLater()
        self.app.quit()

with open('/blah/blah/blah/blah/blah.txt') as f:
    urls = f.read().splitlines()

    for i in urls:
        r = Render(i)
        soup = BeautifulSoup(unicode(r.frame.toHtml()))
        summary = soup.find('div',{'style' : 'padding-top:10px;'})
        tables = summary.find('tbody')
        count = 0
        print 
        for row in tables.findAll('tr'):
            for cell in row.findAll('td'):
                data = cell.getText()
                if (count < 15):
                    data = data + ';'
                    print data, 
                count += 1
                if (count==16):
                    print data
                    count = 0       

嗯,那就是代码。我得到2循环的with循环之前它告诉我分段错误...... :( 换句话说,我会从txt中的6个中删除2个url。

提前感谢您的帮助

1 个答案:

答案 0 :(得分:2)

我设法重现了这个问题。以下代码导致Python失败(在Windows上)。无需所有文件读取和BeautifulSoup代码:

for _ in range(3):
    r = Render('google.com')

如果我确保在创建第二个Render对象之前删除了第一个for _ in range(3): r = Render('google.com') del r 对象,那么就没有错误:

QApplication

我发现this related question表示你不能在一个进程中拥有多个PyQt应用程序。我不熟悉PyQt,所以不知道你是如何解决这个问题的。它可能很简单,但你必须要搜索一下。

此外,this question has code almost identical to yoursa very good answer显示如何创建单个@media (min-width: 480px) .row { margin-left: -10px; margin-right: -10px; } .row, #content-wrapper .fc-section__inner, .fc-section-outer .fc-section-row, #testimonial .fc-section__inner, footer .fc-section__inner { margin-left: -15px; margin-right: -15px; } .row, #content .fc-section__inner, #testimonial .fc-section__inner, footer .fc-section__inner { margin-left: -15px; margin-right: -15px; } 并获取多个网址。您的问题可能应该作为副本关闭。