def getDataFromCsv(empNum):
result = []
try:
strList = []
with open('data.csv', encoding='gb2312') as f:
strList = f.readlines()
except IOError:
print("没有找到CSV文件或读取文件失败, 获取CSV数据步骤跳过")
return result
del strList[0]
for line in strList:
items = line.split(",")
if items[0] == empNum:
result.append({
"date":items[1],
"hours": str.strip(items[2])
})
if len(result) == 0:
print("\n未找您到当月的数据")
return result
print("\n读取CSV数据完毕,数据如下")
for item in result:
print("日期:" + str(item["date"]) + " 工时: " + str(item["hours"]) + " h")
print()
return result
#print(getDataFromCsv("E00010678811"))
# coding=utf-8
import urllib.request, urllib.parse, urllib.error
import http.cookiejar
import json
import re
URL_INNER = "http://timesheetv2.paic.com.cn/timesheet/login?loginType=login"
URL_EX = "http://timesheetv2.paic.com.cn/timesheet/j_security_check"
URL_ROOT = ""
inner = ""
while True:
print("\n您是否为内部员工?(Y/N)")
inner="N"
break
print("\n请输入UM账号:")
userName = "ex-wangyuzhen002"
print("\n请输入UM密码:")
password = "PUBLIc@1991"
if inner == "Y" or inner == "y":
URL_ROOT = URL_INNER
else:
URL_ROOT = URL_EX
values = {
'j_username': userName,
'j_password': password,
'SMAUTHREASON': '0'
}
print("登录开始...")
print("登录请求发送...")
postdata = urllib.parse.urlencode(values).encode()
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
headers = {'User-Agent': user_agent}
cookie_filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(cookie_filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request(URL_ROOT, postdata, headers)
try:
response = opener.open(request).read().decode('gbk')
# 匹配错误信息
rex = r"errorMsg = (.+);"
searchObj = re.search(rex, response, re.M)
if hasattr(searchObj,'group') :
raise RuntimeError(searchObj.group(1))
print("登录成功")
except urllib.error.URLError as e:
print(e.reason)
raise RuntimeError("登录失败")
print("保存COOKIE...")
cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中
print("登录完毕.")
import login
import start
def getItemRex(itemName):
return r"name=\"projectWorkTimes\[\d+\]." + itemName + "\".+value=\"(?P<" + itemName + ">[^\"]*)\".+"
def getProjectIdRex():
return r"value=\"(?P<projectId>[^\"]*)\" selected"
def getNameValueRex(itemName):
return r"name=\"" + itemName + "\".+value=\"(?P<" + itemName + ">[^\"]*)\""
import webClient
import re
import rexManager
def getWorkTime(startDate, endDate):
url = 'http://timesheetv2.paic.com.cn/timesheet/querySheetPersonal.do'
data = {
"start_date" : startDate,
"start_date_bak" : startDate,
"end_date" : endDate,
"server_proj" : "on",
"server_non_proj" : "on",
"non_server" : "on",
"server_projn" : "serverProj",
"server_non_projn" : "serverNonProj",
"work_hour_status" : "all",
"unconfirm" : "on",
"confirmed" : "on",
"unconfirmn" : "0",
"confirmedn" : "1",
"untreadn" : "1",
"confirme_status" : "all",
"taskOwner" : "",
"customerID" : "",
"taskId" : "",
"serviceId" : ""
}
result = webClient.sendPostForm(url, data)
rex = r"(?P<date>\d\d\d\d-\d\d-\d\d).+【.+服务工时:(?P<workTime>\d+.\d+)h.+考勤有效工时:(?P<realWorkTime>[^h]+)h?).+】"
pattern = re.compile(rex)
matchs = pattern.finditer(result)
result = []
for match in matchs:
item = {}
if re.match("\d+\.\d+", match["realWorkTime"]) != None:
item = match.groupdict()
else:
if match["realWorkTime"].find("待同步"):
item = {
"date" : match["date"],
"workTime" : match["workTime"],
"realWorkTime" : "待同步",
}
else:
item = {
"date" : match["date"],
"workTime" : match["workTime"],
"realWorkTime" : "未知(请登录系统查看)",
}
result.append(item)
print(item["date"] + ": 服务工时 [" + item["workTime"] + "] 有效工时 [" + item["realWorkTime"] +"]")
return result
def saveMatchs(result, matchs):
for index, match in enumerate(matchs):
result[index].update(match.groupdict().items())
def queryModifyData(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
propertyNames = ["serviceNo" , "statusT" , "workDate" , "costHours"]
result = []
pattern = re.compile(rexManager.getProjectIdRex())
matchs = pattern.finditer(text)
for match in matchs:
result.append(match.groupdict())
for item in propertyNames:
pattern = re.compile(rexManager.getItemRex(item))
matchs = pattern.finditer(text)
saveMatchs(result, matchs)
return result
def querydepartmentId(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
pattern = re.compile(rexManager.getNameValueRex("departmentId"))
result = pattern.findall(text)[0]
return
def queryEmpNum(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
pattern = re.compile(rexManager.getNameValueRex("empNum"))
result = pattern.findall(text)[0]
return result
def submit(modifyData, startDate, endDate, departmentId):
print("正在提交数据...")
data = {}
for i in range(len(modifyData)):
for key,value in modifyData[i].items():
data["projectWorkTimes[" + str(i) + "]." + key] = value;
data["beginDate"] = startDate
data["endDate"] = endDate
data["isEditTimeSheet"] = "Y"
data["projsNum"] = "0"
data["departmentId"] = departmentId;
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do"
result = webClient.sendPostForm(url, data)
if result.find("操作成功") == -1 :
raise RuntimeError("提交失败")
print("修改完成")
#print(querydepartmentId("2018-11-01","2018-11-21"))
#print(getWorkTime("2018-11-01","2018-11-21"))
#print(queryModifyData("2018-11-01","2018-11-21"))
import service
import re
import timeUtil
import csvLoader
print("\n请手动登录日报系统,批量创建日报,完毕后按按回车键继续")
input()
print("设置开始时间:" + timeUtil.getStartDate())
print("设置结束时间:" + timeUtil.getEndDate())
departmentId = service.querydepartmentId(timeUtil.getStartDate(), timeUtil.getEndDate())
print("唯一部门Id:" + departmentId)
empNum = service.queryEmpNum(timeUtil.getStartDate(), timeUtil.getEndDate())
print("员工E代码:" + str(empNum))
print("\n若您有本月工时的CSV文件,请拷贝到当前目录下,并命名为data.csv。若没有,可以忽略。操作完毕后,按回车键继续")
input()
print("开始查询日报系统的填写情况...")
csvData = csvLoader.getDataFromCsv(empNum)
csvDataDict = {}
for item in csvData:
csvDataDict[item["date"]] = item
workTimeData = service.getWorkTime(timeUtil.getStartDate(), timeUtil.getEndDate())
print("查询到填写的日报共" + str(len(workTimeData)) + "条")
if len(workTimeData) == 0:
raise RuntimeError("未查询到日报,请登录日报系统创建")
workTimeDict = {}
for item in workTimeData:
workTimeDict[item["date"]] = item
modfiyData = service.queryModifyData(timeUtil.getStartDate(), timeUtil.getEndDate())
for item in modfiyData:
if re.match("\d+.\d+", workTimeDict[item["workDate"]]["realWorkTime"]):
item["costHours"] = workTimeDict[item["workDate"]]["realWorkTime"]
else:
if item["workDate"] in csvDataDict.keys() :
print("加载csv数据: 日期" + csvDataDict[item["workDate"]]["date"] + " 工时 " + csvDataDict[item["workDate"]]["hours"])
item["costHours"] = csvDataDict[item["workDate"]]["hours"]
service.submit(modfiyData, timeUtil.getStartDate(), timeUtil.getEndDate(), departmentId)
if len(csvData) > 0:
print("开始提交csv数据..")
print()
print("复查开始...")
workTimeData = service.getWorkTime(timeUtil.getStartDate(), timeUtil.getEndDate())
print("复查完毕.")
for item in workTimeData:
if re.match("\d+.\d+", item["workTime"]):
if float(item["workTime"]) < 7.58 :
print("注意!您有小于7.58的数据, 建议到系统内核对.")
print("\n程序执行完毕,按任意键结束^_^")
input()
import datetime
def getStartDate():
now = datetime.datetime.now()
time = datetime.datetime.strptime(str(now.year) + "-" + str(now.month) + "-" + "1", "%Y-%m-%d")
return time.strftime("%Y-%m-%d")
def getEndDate():
now = datetime.datetime.now()
# 计算下个月第一天
month = now.month
year = now.year
if month == 12:
month = 0
year = year + 1
futureMouthFirstDay = datetime.datetime.strptime(str(year) + "-" + str(month + 1) + "-" + "01", "%Y-%m-%d")
# 当月最后一天
lastDay = futureMouthFirstDay - datetime.timedelta(days=1)
time = datetime.datetime.strptime(str(lastDay.year) + "-" + str(lastDay.month) + "-" + str(lastDay.day), "%Y-%m-%d")
return time.strftime("%Y-%m-%d")
import urllib.request
import json
import http.cookiejar
print("加载COOKIE...")
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar()
cookie.load(filename, ignore_discard=True, ignore_expires=True)
handler= urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
print("完毕.")
def sendPostForm(url, data):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
encodeData = urllib.parse.urlencode(data).encode('utf-8')
request = urllib.request.Request(url, encodeData, headers)
result = opener.open(request).read().decode('gbk')
return result
def sendGet(url):
request = urllib.request.Request(url)
result = opener.open(request).read().decode('gbk')
return result
def getDataFromCsv(empNum):
result = []
try:
strList = []
with open('data.csv', encoding='gb2312') as f:
strList = f.readlines()
except IOError:
print("没有找到CSV文件或读取文件失败, 获取CSV数据步骤跳过")
return result
del strList[0]
for line in strList:
items = line.split(",")
if items[0] == empNum:
result.append({
"date":items[1],
"hours": str.strip(items[2])
})
if len(result) == 0:
print("\n未找您到当月的数据")
return result
print("\n读取CSV数据完毕,数据如下")
for item in result:
print("日期:" + str(item["date"]) + " 工时: " + str(item["hours"]) + " h")
print()
return result
#print(getDataFromCsv("E00010678811"))
# coding=utf-8
import urllib.request, urllib.parse, urllib.error
import http.cookiejar
import json
import re
URL_INNER = "http://timesheetv2.paic.com.cn/timesheet/login?loginType=login"
URL_EX = "http://timesheetv2.paic.com.cn/timesheet/j_security_check"
URL_ROOT = ""
inner = ""
while True:
print("\n您是否为内部员工?(Y/N)")
inner="N"
break
print("\n请输入UM账号:")
userName =
print("\n请输入UM密码:")
password =
if inner == "Y" or inner == "y":
URL_ROOT = URL_INNER
else:
URL_ROOT = URL_EX
values = {
'j_username': userName,
'j_password': password,
'SMAUTHREASON': '0'
}
print("登录开始...")
print("登录请求发送...")
postdata = urllib.parse.urlencode(values).encode()
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
headers = {'User-Agent': user_agent}
cookie_filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(cookie_filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request(URL_ROOT, postdata, headers)
try:
response = opener.open(request).read().decode('gbk')
# 匹配错误信息
rex = r"errorMsg = (.+);"
searchObj = re.search(rex, response, re.M)
if hasattr(searchObj,'group') :
raise RuntimeError(searchObj.group(1))
print("登录成功")
except urllib.error.URLError as e:
print(e.reason)
raise RuntimeError("登录失败")
print("保存COOKIE...")
cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中
print("登录完毕.")
import login
import start
def getItemRex(itemName):
return r"name=\"projectWorkTimes\[\d+\]." + itemName + "\".+value=\"(?P<" + itemName + ">[^\"]*)\".+"
def getProjectIdRex():
return r"value=\"(?P<projectId>[^\"]*)\" selected"
def getNameValueRex(itemName):
return r"name=\"" + itemName + "\".+value=\"(?P<" + itemName + ">[^\"]*)\""
import webClient
import re
import rexManager
def getWorkTime(startDate, endDate):
url = 'http://timesheetv2.paic.com.cn/timesheet/querySheetPersonal.do'
data = {
"start_date" : startDate,
"start_date_bak" : startDate,
"end_date" : endDate,
"server_proj" : "on",
"server_non_proj" : "on",
"non_server" : "on",
"server_projn" : "serverProj",
"server_non_projn" : "serverNonProj",
"work_hour_status" : "all",
"unconfirm" : "on",
"confirmed" : "on",
"unconfirmn" : "0",
"confirmedn" : "1",
"untreadn" : "1",
"confirme_status" : "all",
"taskOwner" : "",
"customerID" : "",
"taskId" : "",
"serviceId" : ""
}
result = webClient.sendPostForm(url, data)
rex = r"(?P<date>\d\d\d\d-\d\d-\d\d).+【.+服务工时:(?P<workTime>\d+.\d+)h.+考勤有效工时:(?P<realWorkTime>[^h]+)h?).+】"
pattern = re.compile(rex)
matchs = pattern.finditer(result)
result = []
for match in matchs:
item = {}
if re.match("\d+\.\d+", match["realWorkTime"]) != None:
item = match.groupdict()
else:
if match["realWorkTime"].find("待同步"):
item = {
"date" : match["date"],
"workTime" : match["workTime"],
"realWorkTime" : "待同步",
}
else:
item = {
"date" : match["date"],
"workTime" : match["workTime"],
"realWorkTime" : "未知(请登录系统查看)",
}
result.append(item)
print(item["date"] + ": 服务工时 [" + item["workTime"] + "] 有效工时 [" + item["realWorkTime"] +"]")
return result
def saveMatchs(result, matchs):
for index, match in enumerate(matchs):
result[index].update(match.groupdict().items())
def queryModifyData(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
propertyNames = ["serviceNo" , "statusT" , "workDate" , "costHours"]
result = []
pattern = re.compile(rexManager.getProjectIdRex())
matchs = pattern.finditer(text)
for match in matchs:
result.append(match.groupdict())
for item in propertyNames:
pattern = re.compile(rexManager.getItemRex(item))
matchs = pattern.finditer(text)
saveMatchs(result, matchs)
return result
def querydepartmentId(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
pattern = re.compile(rexManager.getNameValueRex("departmentId"))
result = pattern.findall(text)[0]
return result
def queryEmpNum(startDate, endDate):
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do?start_date=" + startDate + "&end_date=" + endDate
text = webClient.sendGet(url)
pattern = re.compile(rexManager.getNameValueRex("empNum"))
result = pattern.findall(text)[0]
return result
def submit(modifyData, startDate, endDate, departmentId):
print("正在提交数据...")
data = {}
for i in range(len(modifyData)):
for key,value in modifyData[i].items():
data["projectWorkTimes[" + str(i) + "]." + key] = value;
data["beginDate"] = startDate
data["endDate"] = endDate
data["isEditTimeSheet"] = "Y"
data["projsNum"] = "0"
data["departmentId"] = departmentId;
url = "http://timesheetv2.paic.com.cn/timesheet/modifySheet.do"
result = webClient.sendPostForm(url, data)
if result.find("操作成功") == -1 :
raise RuntimeError("提交失败")
print("修改完成")
#print(querydepartmentId("2018-11-01","2018-11-21"))
#print(getWorkTime("2018-11-01","2018-11-21"))
#print(queryModifyData("2018-11-01","2018-11-21"))
import service
import re
import timeUtil
import csvLoader
print("\n请手动登录日报系统,批量创建日报,完毕后按按回车键继续")
input()
print("设置开始时间:" + timeUtil.getStartDate())
print("设置结束时间:" + timeUtil.getEndDate())
departmentId = service.querydepartmentId(timeUtil.getStartDate(), timeUtil.getEndDate())
print("唯一部门Id:" + departmentId)
empNum = service.queryEmpNum(timeUtil.getStartDate(), timeUtil.getEndDate())
print("员工E代码:" + str(empNum))
print("\n若您有本月工时的CSV文件,请拷贝到当前目录下,并命名为data.csv。若没有,可以忽略。操作完毕后,按回车键继续")
input()
print("开始查询日报系统的填写情况...")
csvData = csvLoader.getDataFromCsv(empNum)
csvDataDict = {}
for item in csvData:
csvDataDict[item["date"]] = item
workTimeData = service.getWorkTime(timeUtil.getStartDate(), timeUtil.getEndDate())
print("查询到填写的日报共" + str(len(workTimeData)) + "条")
if len(workTimeData) == 0:
raise RuntimeError("未查询到日报,请登录日报系统创建")
workTimeDict = {}
for item in workTimeData:
workTimeDict[item["date"]] = item
modfiyData = service.queryModifyData(timeUtil.getStartDate(), timeUtil.getEndDate())
for item in modfiyData:
if re.match("\d+.\d+", workTimeDict[item["workDate"]]["realWorkTime"]):
item["costHours"] = workTimeDict[item["workDate"]]["realWorkTime"]
else:
if item["workDate"] in csvDataDict.keys() :
print("加载csv数据: 日期" + csvDataDict[item["workDate"]]["date"] + " 工时 " + csvDataDict[item["workDate"]]["hours"])
item["costHours"] = csvDataDict[item["workDate"]]["hours"]
service.submit(modfiyData, timeUtil.getStartDate(), timeUtil.getEndDate(), departmentId)
if len(csvData) > 0:
print("开始提交csv数据..")
print()
print("复查开始...")
workTimeData = service.getWorkTime(timeUtil.getStartDate(), timeUtil.getEndDate())
print("复查完毕.")
for item in workTimeData:
if re.match("\d+.\d+", item["workTime"]):
if float(item["workTime"]) < 7.58 :
print("注意!您有小于7.58的数据, 建议到系统内核对.")
print("\n程序执行完毕,按任意键结束^_^")
input()
import datetime
def getStartDate():
now = datetime.datetime.now()
time = datetime.datetime.strptime(str(now.year) + "-" + str(now.month) + "-" + "1", "%Y-%m-%d")
return time.strftime("%Y-%m-%d")
def getEndDate():
now = datetime.datetime.now()
# 计算下个月第一天
month = now.month
year = now.year
if month == 12:
month = 0
year = year + 1
futureMouthFirstDay = datetime.datetime.strptime(str(year) + "-" + str(month + 1) + "-" + "01", "%Y-%m-%d")
# 当月最后一天
lastDay = futureMouthFirstDay - datetime.timedelta(days=1)
time = datetime.datetime.strptime(str(lastDay.year) + "-" + str(lastDay.month) + "-" + str(lastDay.day), "%Y-%m-%d")
return time.strftime("%Y-%m-%d")
import urllib.request
import json
import http.cookiejar
print("加载COOKIE...")
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar()
cookie.load(filename, ignore_discard=True, ignore_expires=True)
handler= urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
print("完毕.")
def sendPostForm(url, data):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
encodeData = urllib.parse.urlencode(data).encode('utf-8')
request = urllib.request.Request(url, encodeData, headers)
result = opener.open(request).read().decode('gbk')
return result
def sendGet(url):
request = urllib.request.Request(url)
result = opener.open(request).read().decode('gbk')
return result
def getDataFromCsv(empNum):
result = []
try:
strList = []
~~~python
网友评论