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

yipeiwu_com5年前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】:按任意键退出')

相关文章

windows及linux环境下永久修改pip镜像源的方法

windows及linux环境下永久修改pip镜像源的方法

一、在windows环境下修改pip镜像源的方法(以python3.5为例) (1):在windows文件管理器中,输入 %APPDATA% (2):会定位到一个新的目录下,在该目...

python list删除元素时要注意的坑点分享

我们直接先给出输出与预期不同的代码 In[28]: a = [1,2,3,4,5,6] In[29]: for i in a: ...: a.remove(i) ...:...

Python实现从百度API获取天气的方法

本文实例讲述了Python实现从百度API获取天气的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:__author__ = 'saint' import os im...

对python3新增的byte类型详解

对python3新增的byte类型详解

在python2中字节类型同字符类型区分不大,但是在python3中最重要的特性是对文本和二进制数据做了更加清晰的区分,文本总是Unicode,由字符类型表示,而二进制数据则由byte类...

深入理解Python中的super()方法

前言 python的类分别有新式类和经典类,都支持多继承。在类的继承中,如果你想要重写父类的方法而不是覆盖的父类方法,这个时候我们可以使用super()方法来实现 python语言与C+...