python自動生成證件號的方法示例

前言

在跟進需求的時候,往往涉及到測試,特別是需要用到身份信息的時候,總繞不開身份證號碼這個話題。之前在跟一個互聯網產品的時候,需要很多身份證做測試,又不想裝太多軟件自動生成(有需要的小夥伴可自行搜索身份證號碼自動生成軟件),按照身份證規則現編也比較浪費時間,在處理身份數據時,Python就非常有用瞭。

方法示例如下

# Author:BeeLe
# -*-coding:utf-8-*-

# 生成身份證號碼主程序
import urllib.request
import requests
from bs4 import BeautifulSoup
import re
import random
import time
import lxml


# class IDCard():
def regiun(strarr):
 '''生成身份證前六位'''
 first = random.choice(strarr)
 return first


def year():
 '''生成年份'''
 # 1978為第一代身份證執行年份,now-18直接過濾掉小於18歲出生的年份
 now = time.strftime('%Y')
 second = random.randint(1978, int(now) - 18)
 # age = int(now)-second
 # print('隨機生成的身份證人員年齡為:'+str(age))
 return second


def month():
 '''生成月份'''
 three = random.randint(1, 12)
 if three < 10:
 three = '0' + str(three)
 return three
 else:
 return three


def day(year, month):
 '''生成日期'''
 four = getDay(year, month)
 # 日期小於10以下,前面加上0填充
 if four < 10:
 four = '0' + str(four)
 return four
 return four


def getDay(year, month):
 '''根據傳來的年月份返回日期'''
 # 1,3,5,7,8,10,12月為31天,4,6,9,11為30天,2月閏年為28天,其餘為29天
 aday = 0
 if month in (1, 3, 5, 7, 8, 10, 12):
 aday = random.randint(1, 31)
 elif month in (4, 6, 9, 11):
 aday = random.randint(1, 30)
 else:
 # 即為2月判斷是否為閏年
 if ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
  aday = random.randint(1, 28)
 else:
  aday = random.randint(1, 29)
 return aday


def randoms():
 '''生成身份證後四位'''
 five = random.randint(1, 9999)
 if five < 10:
 five = '000' + str(five)
 elif 10 < five < 100:
 five = '00' + str(five)
 elif 100 < five < 1000:
 five = '0' + str(five)
 return five

# if __name__ == '__main__':

def idcard():
 # 通過爬取網頁獲取到身份證前六位
 url = 'https://wenku.baidu.com/view/a55406b919e8b8f67d1cb920'
 request = urllib.request.Request(url) # 獲取url的網頁源碼
 response = urllib.request.urlopen(request)
 html = response.read()
 soup = BeautifulSoup(html, 'lxml')
 strarr = []
 for info in soup.find_all(class_='expanded'):
 pattern = re.compile(r'\d{6}')
 b = re.findall(pattern, info.text)
 for item in b:
  strarr.append(item)

 for i in range(1, 2):
 first = regiun(strarr)
 second = year()
 three = month()
 four = day(second, three)
 last = randoms()
 IDCard = str(first) + str(second) + str(three) + str(four) + str(last)
 # print('隨機生成的身份證號碼為:' + IDCard)
 return IDCard
# Idcard = idcard

總結

到此這篇關於python自動生成證件號的文章就介紹到這瞭,更多相關python自動生成證件號內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: