python正则匹配查询港澳通行证办理进度示例分享

yipeiwu_com6年前Python基础

复制代码 代码如下:

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

'''
利用正则表达式从上步获取的网页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】:按任意键退出')

相关文章

Pycharm取消py脚本中SQL识别的方法

Pycharm取消py脚本中SQL识别的方法

Pycharm默认可以识别py脚本中的SQL语句,本身很不错,但当SQL拼接时就显示的代码特别难看,找了好久,终于知道怎么关闭SQL识别功能了。 如下图,把勾去掉就可以了。 以上这篇P...

理论讲解python多进程并发编程

理论讲解python多进程并发编程

一、什么是进程 进程:正在进行的一个过程或者说一个任务。而负责执行任务则是cpu。 二、进程与程序的区别 程序:仅仅是一堆代 进程:是指打开程序运行的过程 三、并发与并行 并发与并行是指...

Python实现串口通信(pyserial)过程解析

pyserial模块封装了对串口的访问,兼容各种平台。 安装 pip insatll pyserial 初始化 简单初始化示例 import serial ser = se...

Python中的迭代器与生成器高级用法解析

迭代器 迭代器是依附于迭代协议的对象——基本意味它有一个next方法(method),当调用时,返回序列中的下一个项目。当无项目可返回时,引发(raise)StopIteration异常...

Python面向对象之继承和多态用法分析

Python面向对象之继承和多态用法分析

本文实例讲述了Python面向对象之继承和多态用法。分享给大家供大家参考,具体如下: Python 类的继承和多态 Python 类的继承 在OOP(Object Oriented Pr...