簡單的一個例子,是以前用Dephi寫的,前不久剛實作了一個在Python中使用Delphi控件來編寫界面程式,于是趁熱寫一個類似的的查詢方案。
本執行個體是通過www.ip138.com這個網站來查詢的,這裡需要的幾個知識點,就是用Python模拟網頁送出資料,獲得資料傳回資訊,以及對傳回的Html資訊進行解析,模拟Http送出,Python自帶有一個urllib和urllib2這兩個庫,相當友善,隻是奇怪,為什麼不将兩個庫合并成一個,這樣來的更友善。然後就是窗體了,窗體還是用我之前寫的一個Python子產品DxVcl,就是可以在Python中調用Delphi界面控件的一個子產品庫。下面就貼上代碼,相當簡單的!
<a></a>
#-*-coding: gb2312 -*-
import urllib,urllib2,HTMLParser
from DxVcl import *
class MyParser(HTMLParser.HTMLParser):
def reset(self):
self._isInTd = False
self._retdata = []
HTMLParser.HTMLParser.reset(self)
def handle_starttag(self,tag,attris):
self._isInTd = tag == 'td'
def handle_endtag(self,tag):
if self._isInTd:
def handle_data(self,data):
self._retdata.append(data)
class MainForm(Form):
def __init__(self,Owner):
self.Caption = '查詢手機歸屬地'
self.Position = 5
self.BorderStyle = 3
self.Width = 303
self.Height = 375
self.lbl = Label(self)
self.lbl.SetProps(Parent = self,Caption = '手機号碼')
self.lbl.SetBounds(16,8,60,13)
self.EdtPhone = Edit(self)
self.EdtPhone.SetProps(Parent = self,Text = '')
self.EdtPhone.SetBounds(77,3,121,21)
self.Button1 = Button(self)
self.Button1.SetProps(Parent = self,Caption = '查詢')
self.Button1.SetBounds(204,1,75,25)
self.Button1.OnClick = self.Button1Click
self.Memo1 = Memo(self)
self.Memo1.Parent = self
self.Memo1.SetBounds(16,32,263,297)
def Button1Click(self,Sender):
postdata = urllib.urlencode([('action','mobile'),('mobile',self.EdtPhone.Text)])
req = urllib2.Request('http://www.ip138.com:8080/search.asp')
fd = urllib2.urlopen(req,postdata)
h = fd.read()
my = MyParser()
my.feed(h)
self.Memo1.Lines.Clear()
for data in my._retdata:
self.Memo1.Lines.Add(data)
def main():
FreeConsole()
Application.Initialize()
Application.Title = '查詢手機歸屬'
f = MainForm(Application)
f.Show()
Application.Run()
if __name__=='__main__':
main()
運作之後的界面
本文轉自 不得閑 部落格園部落格,原文連結: http://www.cnblogs.com/DxSoft/archive/2011/04/07/2007871.html ,如需轉載請自行聯系原作者