前言
最近做了几个简单的爬虫python程序,于是就想做个窗口看看效果。
首先是,窗口的话,以前没怎么接触过,就先考虑用Qt制作简单的ui。这里用前面sinanews的爬虫脚本为例,制作一个获取当天sina头条新闻的窗口。
生成py文件后,运行该py文件,这里窗口我只是随便拖了几个组件进去,主要的text browser用于显示获取到的sinanews。
首先贴一下我的配置
官方下载:
Python 3.3.3
PyQt5-5.2.1 for Py3.3(当安装完Python3.3后,安装对应PyQt,其会找到Python安装目录,不用更改安装目录)
本地下载:
Python 3.3.3
PyQt5-5.2.1 for Py3.3(当安装完Python3.3后,安装对应PyQt,其会找到Python安装目录,不用更改安装目录)
Python3.3默认是没有安装pip的,需要下载get-pip.py运行之后,提示安装成功。
接下来就要安装一些必要的组件了。为了安装方便,先把pip添加进环境变量。
下面我们就可以用pip命令安装组件了。
先把sina_news.py贴出来,观察需要哪些组件。
import requestsfrom bs4 import BeautifulSoupres = requests.get('http://news.sina.com.cn/china/')res.encoding = 'utf-8'soup = BeautifulSoup(res.text,'html.parser')for news in soup.select('.news-item'): if len(news.select('h2')) > 0: h2 = news.select('h2')[0].text a = news.select('a')[0]['href'] time = news.select('.time')[0].text print(time,h2,a)
发现import requests,import BeautifulSoup 所以先来安装这些组件
pip install requestspip install BeautifulSoup4
当我们把这段代码贴进窗口代码后:
x.py
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'x.ui'## Created by: PyQt5 UI code generator 5.8.1## WARNING! All changes made in this file will be lost!import sysimport requestsfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom bs4 import BeautifulSoupclass Ui_x(object): def getNews(): res = requests.get('http://news.sina.com.cn/china/') res.encoding = 'utf-8' soup = BeautifulSoup(res.text,'html.parser') title = [] for news in soup.select('.news-item'): if len(news.select('h2')) > 0: h2 = news.select('h2')[0].text title.append(h2) a = news.select('a')[0]['href'] time = news.select('.time')[0].text return '/n'.join(title) def setupUi(self, x): x.setObjectName("x") x.resize(841, 749) self.timeEdit = QtWidgets.QTimeEdit(x) self.timeEdit.setGeometry(QtCore.QRect(310, 10, 141, 31)) self.timeEdit.setObjectName("timeEdit") self.dateEdit = QtWidgets.QDateEdit(x) self.dateEdit.setGeometry(QtCore.QRect(100, 10, 191, 31)) self.dateEdit.setObjectName("dateEdit") self.textBrowser = QtWidgets.QTextBrowser(x) self.textBrowser.setGeometry(QtCore.QRect(60, 80, 701, 641)) self.textBrowser.setObjectName("textBrowser") self.retranslateUi(x) QtCore.QMetaObject.connectSlotsByName(x) def retranslateUi(self, x): _translate = QtCore.QCoreApplication.translate x.setWindowTitle(_translate("x", "x"))if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_x() ui.setupUi(Form) Form.show() ui.textBrowser.setText(Ui_x.getNews()) sys.exit(app.exec_())
新闻热点
疑难解答