如何将url添加到书签?

时间:2014-09-23 06:35:04

标签: python-2.7 pyqt4 bookmarks qtwebkit

我正在使用PyQt4使用QtWebKit创建自定义浏览器,但我仍然坚持从浏览器保存书签。有谁知道如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

你对如何完成这一点有点模糊,所以我想说我们想要使用从名为bookmarks_Btn的UI文件导入的按钮。您需要使用pickle模块。

以下是示例代码...

from PyQt4 import QtCore, QtGui, QtWebKit, uic
import pickle

class window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(httpWidget, self).__init__(parent)
        self.ui = uic.loadUi('mybrowser.ui')
        self.ui.setupUi(self)      

    def bookmarksLoad(self):
        print 'Loading bookmarks'
        try:
            bookOpen = open('bookmarks.txt', 'rb')
            bookmarks = pickle.load(bookOpen)
            bookOpen.close()
            print bookmarks # Not necessary, but for example purposes

            # Here you decide how "bookmarks" variable is displayed.

        except:
            bookOpen = open('bookmarks.txt', 'wb')
            bookmarks = 'http://www.stackoverflow.com'
            bookWrite = pickle.dump(bookmarks, bookOpen)
            bookOpen.close()
            print bookmarks # Not necessary, but for example purposes

            # Here you decide how "bookmarks" variable is displayed.

     QtCore.QObject.connect(self.ui.bookmarks_Btn, QtCore.SIGNAL('clicked()'), self.bookmarksLoad)
    self.ui.show()

def bookmarks():
    url = input 'Enter a URL: '
    bookOpen = open('bookmarks.txt', 'wb')
    bookOpen.write(url)
    bookOpen.close()
    print 'Website bookmarked!'


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    run = window()
    bookmarks()
    sys.exit(app.exec_())

# You add on here, for example, deleting bookmarks.

但是,如果您希望从地址栏(名为address)检索它,请进行以下更改...

# In the bookmarks function...
global url # Add at beginning
# Remove the input line.

# Add at end of __init__ in window class:
url = self.ui.address.text()
global url

这几乎是基础知识。请注意我通常在Python 3和PyQt5中编程,所以如果有任何错误,请告诉我:)