Python获取法定节假日
import requests
from bs4 import BeautifulSoup as BS
# 获取指定月份节假日
def get_holidays(year, month):
result = {}
url = f"https://www.rili.com.cn/wannianli/{year}/{month}/"
content = requests.get(url)
bs = BS(content.text)
holidays = ['春节','元旦','除夕','元宵节','清明节','劳动节','端午节','中秋节','国庆节']
tds = bs.find("table").find("table").find_all("td")
for td in tds:
if 'noby' in td['class']:
continue
day = td.select(".riwai>.ri")[0].text
name1 = td.select(".riwai>.jie")
name2 = td.select(".riwai>.r2")
if len(name1)>0:
name = name1[0].text
if len(name2)>0:
name = name2[0].text
if name in holidays:
result[f"{year}-{month}-{day}"] = name
return result
if __name__=="__main__":
holidays = {}
for year in range(1990, 1995):
for month in range(1, 13):
holidays.update(get_holidays(year,month))
print(holidays)
{'1990-1-1': '元旦', '1990-1-26': '除夕', '1990-1-27': '春节', '1990-2-10': '元宵节', '1990-4-5': '清明节', '1990-5-1': '劳动节', '1990-5-28': '端午节', '1990-10-1': '国庆节', '1990-10-3': '中秋节', '1991-1-1': '元旦', '1991-2-14': '除夕', '1991-2-15': '春节', '1991-3-1': '元宵节', '1991-4-5': '清明节', '1991-5-1': '劳动节', '1991-6-16': '端午节', '1991-9-22': '中秋节', '1991-10-1': '国庆节', '1992-1-1': '元旦', '1992-2-3': '除夕', '1992-2-4': '春节', '1992-2-18': '元宵节', '1992-4-4': '清明节', '1992-5-1': '劳动节', '1992-6-5': '端午节', '1992-9-11': '中秋节', '1992-10-1': '国庆节', '1993-1-1': '元旦', '1993-1-22': '除夕', '1993-1-23': '春节', '1993-2-6': '元宵节', '1993-4-5': '清明节', '1993-5-1': '劳动节', '1993-6-24': '端午节', '1993-9-30': '中秋节', '1993-10-1': '国庆节', '1994-1-1': '元旦', '1994-2-9': '除夕', '1994-2-10': '春节', '1994-2-24': '元宵节', '1994-4-5': '清明节', '1994-5-1': '劳动节', '1994-6-13': '端午节', '1994-9-20': '中秋节', '1994-10-1': '国庆节'}