Python語言實現手機號歸屬地的方法__Python
來源:互聯網
上載者:User
現在騙子越來越猖獗,大家每天接到的陌生騷擾電話不計其數,現在手機有個功能能顯示手機來電的歸屬地,最近自己有空餘時間,在網上查了下,發現使用的是Python 開發( http://www.maiziedu.com/course/python/ )語言編寫的,在 Python 中使用 Delphi 空間來編寫介面程式,於是自己趁熱寫了一個類型的查詢方案。 本執行個體是通過 www.ip138.com 這個網站來查詢的,這裡需要的幾個知識點,就是用 Python 類比網頁提交資料,獲得資料返回資訊,以及對返回的 Html 資訊進行解析,類比 Http 提交 ,Python 內建有一個 urllib 和 urllib2 這兩個庫,相當方便,只是奇怪,為什麼不將兩個庫合并成一 個,這樣來的更方便。然後就是表單了,表單還是用我之前寫的一個 Python 模組 DxVcl ,就是可以在 Python 中調用 Delphi 介面控制項的一個模 塊庫。下面就貼上代碼,相當簡單的。 #-*-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: self._isInTd = False def handle_data(self,data): if self._isInTd: 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() 運行之後的介面