python正則匹配查詢港澳通行證辦理進度樣本分享_python

來源:互聯網
上載者:User

複製代碼 代碼如下:

import socket
import re

'''
廣東省公安廳出入境政務服務網護照,通行證辦理進度查詢。
分析網址格式為 http://www.gdcrj.com/wsyw/tcustomer/tcustomer.do?&method=find&applyid=社會安全號碼碼
構造socket請求網頁html,利用正則匹配出查詢結果
'''
def gethtmlbyidentityid(identityid):
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 host = 'www.gdcrj.com';
 suburl = '/wsyw/tcustomer/tcustomer.do?&method=find&applyid={0}'
 port = 80;

 remote_ip = socket.gethostbyname(host)
 s.connect((remote_ip , port))

 print('【INFO】:socket串連成功')

 message = 'GET '+ suburl.format(identityid) +' HTTP/1.1\r\nHost: '+ host +'\r\n\r\n'

 # str 2 bytes
 m_bytes = message.encode('utf-8')

 # send bytes
 s.sendall(m_bytes)

 print('【INFO】:遠程下載中...')

 recevstr = ''
 while True:
  # return bytes
  recev = s.recv(4096)
  # bytes 2 str
  recevstr += recev.decode(encoding = 'utf-8', errors = 'ignore')
  if not recev:
   s.close()
   print('【INFO】:遠程下載網頁完成')
   break
 return recevstr

'''
利用Regex從上步擷取的網頁html內容裡找出查詢結果
'''
def getresultfromhtml(htmlstr):
 linebreaks = re.compile(r'\n\s*')
 space = re.compile('( )+')
 resultReg = re.compile(r'\<td class="news_font"\>([^<td]+)\</td\>', re.MULTILINE)

 #去除分行符號和空格
 htmlstr = linebreaks.sub('', htmlstr)
 htmlstr = space.sub(' ', htmlstr)

 #匹配出查詢結果
 result = resultReg.findall(htmlstr)
 for res in result:
  print(res.strip())

if __name__ == '__main__':
 identityid = input('輸入您的社會安全號碼碼(僅限廣東省居民查詢):')
 try:
  identityid = int(identityid)
  print('【INFO】:開始查詢')
  html = gethtmlbyidentityid(identityid)
  getresultfromhtml(html)
  print('【INFO】:查詢成功')
 except:
  print('【WARN】:輸入非法')

 input('【INFO】:按任意鍵退出')

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.