解析日历接口
目标URL:万年日历查询 - 在线日历 (bmcx.com)
1、模拟请求抓包
2、分析源码结构
3、代码逻辑
如果日期左上角标签带有休
或班
的字样,则为需要采集的目标日期;
历遍class属性判断,是否存在wnrl_riqi_xiu(休)
或者wnrl_riqi_ban(班)
;
获取span 标签下的文本信息,代表具体日期以及节日名称;
关键代码:
response = s.get(url, headers=headers, params=payload)
element = etree.HTML(response.text)
html = element.xpath('//div[@class="wnrl_riqi"]')
print('In Working:', year_month)
for _element in html:
# 获取节点属性
item = _element.xpath('./a')[0].attrib
if 'class' in item:
if item['class'] == 'wnrl_riqi_xiu':
tag = '休假'
elif item['class'] == 'wnrl_riqi_ban':
tag = '补班'
else:
pass
_span = _element.xpath('.//text()')
result.append({'Date': year_month + '-' + _span[0], 'Holiday': _span[1], 'Tag': tag})
4、完整代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Joson
# @DateTime: 2020-05-19 10:25
# @Description: https://wannianrili.51240.com/
# @Version: 1.0
import csv
import requests
from lxml import etree
class WanNianRiLi(object):
"""万年日历接口数据抓取
Params:year 四位数年份字符串
"""
def __init__(self, year):
self.year = year
data = self.parseHTML()
self.exportCSV(data)
def parseHTML(self):
"""页面解析"""
url = 'https://wannianrili.51240.com/ajax/'
s = requests.session()
headers = {
'Host': 'wannianrili.51240.com',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Accept': '*/*',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Referer': 'https://wannianrili.51240.com/',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
}
result = []
# 生成月份列表
dateList = [self.year + '-' + '%02d' % i for i in range(1, 13)]
for year_month in dateList:
s = requests.session()
url = 'https://wannianrili.51240.com/ajax/'
payload = {'q': year_month}
response = s.get(url, headers=headers, params=payload)
element = etree.HTML(response.text)
html = element.xpath('//div[@class="wnrl_riqi"]')
print('In Working:', year_month)
for _element in html:
# 获取节点属性
item = _element.xpath('./a')[0].attrib
if 'class' in item:
if item['class'] == 'wnrl_riqi_xiu':
tag = '休假'
elif item['class'] == 'wnrl_riqi_ban':
tag = '补班'
else:
pass
_span = _element.xpath('.//text()')
result.append({'Date': year_month + '-' + _span[0], 'Holiday': _span[1], 'Tag': tag})
print(result)
return result
def exportCSV(self, data):
"""导出CSV"""
headers = ['Date', 'Holiday', 'Tag']
# 如果存入乱码,添加 encoding='utf-8-sig'
with open(self.year + 'Holiday.csv', 'w', newline='')as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(data)
if __name__ == '__main__':
rili = WanNianRiLi('2020')
阅读与下载说明
1.『会员阅览(扣点)』为普通会员扣点(1元=1点)通道,已浏览过的只扣一次。
2.『VIP阅览 (VIP)』 为VIP特权通道,充值成VIP用户直接无任何限制高速在线阅览,VIP会员分包月,包年和终身VIP三种。
3.『免费阅览(免费)』为未付费会员通道,可无任何限制免费阅览该资源,推荐购买点数或充值VIP,以获取超值资源。
4. 阅览的资讯文件过大,根据您的网速而会有相应的延迟,请耐心等待;如果提示其他问题请联系客户解决。
购买点数和充值VIP全部支持支付宝或微信扫码支付,登陆会员中心侧面板>>财务选择相关操作即可。
在线预览主旨方便移动设备使用和临时查看,直观浏览,对需要的文章再下载,预览了的文件且能秒速下载。