|
发表于 2018-1-19 19:48:44
|
显示全部楼层
- import re
- import datetime as dt
- import requests as req
- def get(url):
- return req.get(url).text
- def parse(html):
- res = []
- # 获取第一个tbody
- tbody = re.findall(r'<tbody>(.*?)</tbody>', html)[0]
- # 获取tbody中的所有tr
- trs = re.findall('<tr.*?>(.*?)</tr>', tbody)
- for tr in trs:
- # 从tr中获取开始时间和结束时间的时间节点
- ds = re.findall('datetime="\D*(\d*)-(\d*)-(\d*)\D*"',tr)
- ds = [[int(y) for y in x] for x in ds]
- # 计算放假天数
- if len(ds) == 1:
- days = 1
- elif len(ds) == 2:
- start = dt.date(ds[0][0],ds[0][1],ds[0][2])
- end = dt.date(ds[1][0],ds[1][1],ds[1][2])
- days = (end-start).days + 1
- else:
- raise ValueError("some thing wrong!!!")
- # 获取节日名称
- name = re.findall('class="summary.*?>(.*?)<',tr)[0]
- res.append([ds[0],name,days])
- return res
-
-
- def fun( url ):
- html = get(url)
- res = parse(html)
- print('日期\t\t\t节假日\t\t放假天数')
- for x in res:
- print('%d-%02d-%02d\t\t%s\t\t%d' %(x[0][0],x[0][1],x[0][2],x[1],x[2]))
- s = sum( x[2] for x in res)
- print('总天数为:',s)
- def main():
- url = 'https://publicholidays.cn/zh/2018-dates/'
- fun(url)
- if __name__ == "__main__":
- main()
复制代码
结果:
- 日期 节假日 放假天数
- 2018-01-01 元旦 1
- 2018-02-15 春节 7
- 2018-04-05 清明节 3
- 2018-04-29 劳动节 3
- 2018-06-16 端午节 3
- 2018-09-22 中秋节 3
- 2018-10-01 国庆日 7
- 总天数为: 27
复制代码 |
评分
-
查看全部评分
|