用户输入日期利用python简单实现农历转阳历功能(1901-2099年之间)

#!/usr/bin/env python
# coding=utf-8
# https://gonglinongli.51240.com/
import requests
from bs4 import BeautifulSoup
import re

class Calendar(object):
    def __init__(self):
        # 正则规则,获取网站查询结果value后面的年月日数字
        self.pattern = re.compile(r'value="(.+?)"')
        self.url = "https://gonglinongli.51240.com/"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Referer": "https://gonglinongli.51240.com/",
        }
        # 初始化闰月对应表
        self.run_data =[{'-01':'闰正'},{'-02':'闰二'},{'-03':'闰三'},{'-04':'闰四'},{'-05':'闰五'},{'-06':'闰六'},
                        {'-07':'闰七'},{'-08':'闰八'},{'-09':'闰九'},{'-10':'闰十'},{'-11':'闰冬'},{'-12':'闰腊'}]
    # 判断用户输入的年月日是否符合要求,这个网站1-9要转变为01-09
    def main(self):
        while True:
            try:
                self.nongli_nian = input("请输入农历年份(1901-2099年):")
                if int(self.nongli_nian) in range(1901,2100):
                    break
                else:
                    print("输入有误,请输入1901-2099年内任意年份!")
            except:
                    print("输入有误,请输入1901-2099年内任意年份!")
        while True:
            try:
                nongliyue = input("请输入农历月份(输入0查看闰月帮助信息):")
                if int(nongliyue) in range(-12,13) and nongliyue != '0':
                    self.nongli_yue = calendar.judge_yue(nongliyue)
                    break
                # 这里判断农历闰正月至闰腊月
                elif nongliyue == '0':
                    print("============农历闰月数字表=====================")
                    print("闰正(-01)\t闰二(-02)\t闰三(-03)\t闰四(-04)")
                    print("闰五(-05)\t闰六(-06)\t闰七(-07)\t闰八(-08)")
                    print("闰九(-09)\t闰十(-10)\t闰冬(-11)\t闰腊(-12)")
                    print("==============================================")
                    continue
                else:
                    print("输入有误,请输入正确月份!")
            except:
                print("输入有误,请输入正确月份!")
        while True:
            try:
                nongliri = input("请输入农历日:")
                if int(nongliri) in range(1,31):
                    self.nongli_ri = calendar.judge_ri(nongliri)
                    break
                else:
                    print("输入有误,请输入正确农历日!")
            except:
                    print("输入有误,请输入正确农历日!")

        self.formdata = {
            "nongli_nian": self.nongli_nian,
            "nongli_yue": self.nongli_yue,
            "nongli_ri": self.nongli_ri,
        }
        calendar.judge_date()
    # 将用户输入的月份中1-9转换为01-09
    def judge_yue(self,nongliyue):
        # 如果传过来的值第一位不是0并且是一位数,前面就要加0
        if nongliyue[0] != '0'and len(nongliyue) == 1:
            nongli_yue = '0' + str(nongliyue)
            return nongli_yue
        # 如果是负值,第一位是负号并且长度等于2,类似于-1改成-01
        if nongliyue[0] =='-' and len(nongliyue) == 2:
            nongli_yue = nongliyue[0] + '0' + str(nongliyue[1])
            return nongli_yue
        else:
            return nongliyue
    # 将用户输入的日中1-9转换为01-09
    def judge_ri(self,nongliri):
        # 如果传过来的值第一位不是0并且是一位数,前面就要加0
        if nongliri[0] != '0'and len(nongliri) == 1:
            nongli_ri = '0' + str(nongliri)
            return nongli_ri
        else:
            return nongliri
    def judge_date(self):
        items = []
        response = requests.post(self.url,data=self.formdata,headers=self.headers)
        soup = BeautifulSoup(response.text,'lxml')
        # 查找返回页面的所有包含script标签的内容,形成一个列表
        script_list = soup.select('script')
        for i in script_list:
            # 获取所有包含script标签的内容,并放到items列表里
            script_text = i.get_text()
            items.append(script_text)
        # 如果输入的月份是负值,将结果转变成闰正月之类的显示方式
        for i in range(len((self.run_data))):
            if self.nongli_yue in self.run_data[i].keys():
                self.nongli_yue = self.run_data[i][self.nongli_yue]
        # 在items列表里找出包含‘document.getElementById’字段的内容
        for j in items:
                if 'document.getElementById' in j and 'getElementById("gongli_yue").value' in j:
                    result = self.pattern.findall(j)
                    print('\n'+"农历:%s年%s月%s日,转为阳历为:%s年%s月%s日"%(result[3],self.nongli_yue,result[5],
                                                                    result[0],result[1],result[2]))
                if 'document.getElementById' in j and 'getElementById("gongli_yue").value' not in j:
                    print('对不起,您要查询的日期不正确,请仔细核对。')
                    print('您输入的农历日期为:%s年%s月%s日'%(self.nongli_nian,self.nongli_yue,self.nongli_ri))

if __name__ == "__main__":
    calendar = Calendar()
    calendar.main()

效果如下:

用户输入日期利用python简单实现农历转阳历功能(1901-2099年之间)_第1张图片

你可能感兴趣的:(python,python项目)