수정해야 될거 같은점.(2016-01-27 추가)
1. 종종 start버튼누르면 널 참조 오류같은(?) 느낌이 나면서 프로그램이 그냥 죽는다. 왜 그런지 발견.
2. 필터 추가.(female이 들어가있으면 안보겠다. 이런느낌)
3. 가능하면 창을 하나 더 옆에 추가해서 마우스를 올렸을때 맵도 옆에 같이 보여주기.
코드.
# -*- encoding: utf-8 -*-
import sys, time
from PyQt4 import QtGui, QtCore
import urllib2
import re
import itertools
class MyForm(QtGui.QWidget):
def __init__(self, parent=None):
super(MyForm, self).__init__(parent)
self.separate_part_switch = False
self.down_switch = False
self.separate_part_count = 0
self.information = ''
self.totalcount = 0
self.button_text = ['Expensive','Cheap','Apply']#,'More Expensive','Much Cheaper','The Most Expensive','The Cheapest']
self.button_function = [self.up, self.down, self.apply]#, self.moreup, self.moredown, self.last, self.first]
self.setWindowIcon(QtGui.QIcon('vancouver.ico'))
self.minprice = '0'
self.error = False
self.palette = QtGui.QPalette()
self.palette.setBrush(QtGui.QPalette.Background,QtGui.QBrush(QtGui.QPixmap("background.png")))
self.setPalette(self.palette)
self.button = [QtGui.QPushButton('Find room') for i in range(3)] #추가.
for i in range(len(self.button)):
self.button[i].clicked.connect(self.button_function[i])
self.main_layout = QtGui.QGridLayout()
self.main_layout.addWidget(self.button[0], 0, 1)
self.boxwidget = []
self.search_index = 0
self.setLayout(self.main_layout)
self.setGeometry(400,200,350,50) #추가
self.setWindowTitle('Find a good room in downtown!')
def init_gui(self):
label = QtGui.QLabel('Minimum price($) : ')
self.lineEdit = QtGui.QLineEdit()
self.lineEdit.setGeometry(QtCore.QRect(0, 0, 10, 20))
self.lineEdit.setObjectName('abcdee')
label_space = QtGui.QLabel('Made by Go, <a href="http://qkqhxla1.tistory.com/">blog<a>')
label_space.setOpenExternalLinks(True)
self.main_layout.addWidget(label,300,0)
self.main_layout.addWidget(self.lineEdit,300,1)
self.main_layout.addWidget(self.button[2],300,2)
self.main_layout.addWidget(label_space,300,3)
for i in range(4,len(self.button)+3):
self.main_layout.addWidget(self.button[i-4], 300, i)
def up(self):
self.init_gui()
if self.search_index+100 <= self.totalcount:
self.search_index += 100
self.handleButton()
def down(self):
if self.separate_part_count > 1:
self.separate_part_count -= 1
elif self.separate_part_count == 1:
self.separate_part_count -= 1
self.search_index -= 100
self.separate_part_switch = False
else:
self.search_index -= 100
if self.search_index < 0: self.search_index = 0
self.handleButton()
def apply(self):
self.minprice = self.lineEdit.text()
self.search_index = 0
self.separate_part_switch = False
self.handleButton()
def handleButton(self):
for i in range(self.main_layout.count()): #그릴때마다 매번 하이퍼링크 지우고 새로그림.
self.main_layout.itemAt(i).widget().close()
for i in range(len(self.button)):
self.button[i] = QtGui.QPushButton(self.button_text[i])
self.button[i].clicked.connect(self.button_function[i])
self.init_gui()
QtCore.QTimer.singleShot(0, self.startLoop)
def chunks(self, l, n):
n = max(1, n)
return [l[i:i + n] for i in range(0, len(l), n)]
def get_information(self):
page = urllib2.urlopen('http://vancouver.craigslist.ca/search/van/roo?s='+str(self.search_index)+'&min_price='+str(self.minprice)+'&max_price=1500&query=downtown&sort=priceasc').read()
#print 'http://vancouver.craigslist.ca/search/van/roo?s='+str(self.search_index)+'&min_price='+str(self.minprice)+'&max_price=1500&query=downtown&sort=priceasc'
if page.find('the harvest moon wanes') != -1:
self.search_index = 0
page = urllib2.urlopen('http://vancouver.craigslist.ca/search/van/roo?s='+str(self.search_index)+'&min_price='+str(self.minprice)+'&max_price=1500&query=downtown&sort=priceasc').read()
self.totalcount = re.findall('<span class="totalcount">(\d+)</span>',page)[0]
page = page.split(r'<ul class="rows">')[1].split('<div id="noresult-text">')[0]
href = re.split(r'<li class="result-row"\s+data-pid="\d+">|<li class="result-row"\s+data-pid="\d+"\s+data-repost-of="\d+">',page)[1:]
href = [i for i in href if i.lower().find('downtown') != -1 and i.lower().find('to downtown') == -1]
information = []
for h in href:
link = re.findall(r'<a href="(.*?)"',h)[0]
infor = '%-5s %s' %(re.findall(r'<span class="result-price">(.*?)</span>',h)[0],re.findall(r'<a href=".*?" data-id="\d+" class="result-title hdrlnk">(.*?)</a>',h)[0])
if h.find('<small>') != -1:
infor += re.findall(r'<small>(.*?)</small>',h)[0]
information.append([infor,link])
dic = map(lambda x:[int(re.findall(r'\$(\d+)\s+',x[0])[0]),x[0],x[1]],dict((x[0], x) for x in information).values())
#print map(lambda x:[x[1],x[2]],sorted(dic))
return map(lambda x:[x[1],x[2]],sorted(dic))
def add_hyperlink(self, information, index):
self.boxwidget = []
if self.error:
label = QtGui.QLabel('The Internet access is not stable. Check the Internet first.')
self.main_layout.addWidget(label,index,0,5,0)
self.error = False
for t in information:
label = QtGui.QLabel('<a href="http://vancouver.craigslist.ca'+t[1]+'">'+t[0]+'</a>')
label.setOpenExternalLinks(True)
self.main_layout.addWidget(label,index,0,5,0)
self.boxwidget.append(label)
index += 5
self.setGeometry(400,200,350,300) #추가
for i in range(len(self.button)):
self.button[i].setText(self.button_text[i])
if self.separate_part_switch:
self.separate_part_count += 1
if self.separate_part_count == len(self.information):
self.separate_part_switch = False
self.separate_part_count = 0
def startLoop(self):
if not self.separate_part_switch:
try:
self.information = self.get_information()
except:
self.error = True
if len(self.information) >= 20:
self.separate_part_switch = True
self.information = self.chunks(self.information,20)
index = 0
if self.separate_part_switch:
self.add_hyperlink(self.information[self.separate_part_count],index)
else:
self.add_hyperlink(self.information,index)
app = QtGui.QApplication(sys.argv)
myform = MyForm()
myform.show()
sys.exit(app.exec_())