python自动接派单小程序(电力)

小程序采用python + selenium + requests实现,本来计划只采用selenium库去实现,
但是因为开发环境在内网,并且运行的网站比较老,只兼容IE浏览器。所以有些部分
在后期换成了requests库来发送请求。

总结工作中学习到的内容

  • 首先遇到的是环境问题:在离线环境下安装selenium和requests库依赖了许多库,使用pip安装其实会去网上再去找依赖下载用压缩包去安装会好一些。
  • 因为IE浏览器没有开发者模式,所以IEWebdriver,无法添加cookie(可能是本人愚见,不知道有没有大佬会给IE浏览器添加cookie,实现登录)所以还是选用的Chrome浏览器。
  • 在post请求中ContenType类型是multipart/form-data请求体中的内容是下图这样的格式,这个格式中有个boundry分割符。
    请求内容
  • 遇到的问题是使用selenium中的execute_script()函数进行js注入,学习了使用js提交表单。
	# js注入提交表单
	script = 'document.forms[0].submit()'
	html.execute_script(script)
  • 学会用js给Select下拉框添加option的方法,原来将script标签放在了body的最前面导致html页面的元素还没有加载,找不到Select选项框,所以option标签加载失败,直接用innerHTML添加,好记。
	script1 = """let sel = document.getElementsByName("flowHandleDept")[0];
	            sel.innerHTML = '<option value="0003025828">高压用电班</option>';
	          """
	html.execute_script(script1)

登录页登录获取cookie信息

import requests
from requests import utils


# 实现自动化页面登录,获取cookie和工号
def get_jsessionid():
    """

    :return: cookie是jsessionid内容
    :return: u_name是工号
    """
    # 从src文件夹中的u_name.txt文件中,取出工号u_name
    with open('u_name.txt', 'r') as f:
        u_name = f.read()

    # 从src文件夹中的pwd.txt文件中,取出密码pwd
    with open('pwd.txt', 'r') as p:
        pwd = p.read()

    # 设置请求页面的路径为url
    url = "http://95598.sx.sgcc.com.cn/web/pf/authentication/logon.do"

    # 设置请求内容
    payload = 'clientIPAddr=&clientMacAddr=&clientMachineName=&isNeedRSA=&kind=1&lsEmployee=' + u_name + '&password=' + pwd
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Upgrade-Insecure-Requests': '1'
    }

    # 发送请求
    response = requests.request("POST", url, headers=headers, data=payload)
    # 获取请求的返回的jsessionid
    cookie = utils.dict_from_cookiejar(response.cookies)
    return cookie, u_name

获取主页面的表格信息

from login import get_jsessionid

from selenium import webdriver


# 获取表格页面信息
def dispose():
    """

    :return: browser为已经打开的浏览器对象
    """
    # 获取cookie
    jsessionid, u_name = get_jsessionid()
    # 请求页面
    url = 'http://95598.sx.sgcc.com.cn/web/pf/webdesk/frameWork.jsp?'
    browser = webdriver.Chrome(r'./chromedriver.exe')
    # 实现页面请求
    browser.get(url)
    # 添加cookie信息
    browser.add_cookie({'name': 'logonUsername', 'value': u_name})
    browser.add_cookie({'name': 'JSESSIONID', 'value': jsessionid['JSESSIONID']})
    browser.refresh()
    return browser, jsessionid, u_name

筛选出符合字段进行保存发送

import time
from urllib.parse import quote
from selenium import webdriver
import os
import requests
from get_table import dispose
from selenium.webdriver.support.select import Select


# 处理页面信息完成提交
def deal_task():
    # 获取到浏览器对象和cookie信息
    browser, jsessionid, u_name = dispose()
    # 点击工作薄
    browser.switch_to.frame("MenuFrame")
    browser.switch_to.frame("TreeMenuFrame")
    browser.find_element_by_xpath("//a[@title='工作任务']").click()
    # 点击代办工作单
    browser.find_element_by_id("panelbaritembg2_0").click()
    # 找到表单表格
    browser.switch_to.default_content()
    browser.switch_to.frame("PageFrame")
    browser.switch_to.frame(0)
    table = browser.find_element_by_id("worklistPaginationBodyTable")
    # 表单检索数据
    process_title = table.find_elements_by_xpath("//td[@field='process_title']")  # process_title
    process_type = table.find_elements_by_xpath("//td[@field='process_type']")[0::2]  # process_type	109
    process_no = table.find_elements_by_xpath("//td[@field='process_no']")  # process_no	10909
    app_no = table.find_elements_by_xpath("//td[@field='app_no']")  # app_no
    taskid = table.find_elements_by_xpath("//td[@field='taskid']")  # taskid
    org_no = table.find_elements_by_xpath("//td[@field='org_no']")[0::2]  # org_no	14401
    act_name = table.find_elements_by_xpath("//td[@field='act_name']")  # act_name

    # 筛选出列表中服务申请流程接单分理的工作单
    for n in range(len(act_name)):
        print(process_title[n].text, app_no[n].text, act_name[n].text)
        if process_title[n].text == '服务申请流程' and act_name[n].text == '市(县)接单分理':

            # 点击处理
            url1 = "http://95598.sx.sgcc.com.cn/web/sp/process/worklist/WorklistPaginationAction.do?action=deal"
            payload = 'process_type=' + str(process_type[n].text) + '&process_no=' + str(
                process_no[n].text) + '&app_no=' + str(
                app_no[n].text) + '&taskid=' + str(taskid[n].text) + '&org_no=' + str(
                org_no[n].text) + '&act_name=' + quote(
                act_name[
                    n].text) + '&overReason=&locker=%u7FDF%20%u8273%u4E3D&lockerCode=' + u_name.upper() + '&pageNo=1&linenum=&isOverTime=N'
            # print(payload)
            headers = {'Content-Type': 'application/x-www-form-urlencoded',
                       'Cookie': 'logonUsername=' + u_name + '; JSESSIONID=' + jsessionid['JSESSIONID']}
            response = requests.request("POST", url1, headers=headers, data=payload)

            # 获取表单处理页面地址
            if response.text[0:8] == '/webnull':
                deal_url = 'http://95598.sx.sgcc.com.cn/web/cc/flow/serrequestaccepthandle/serrequestaccepthandle.do?action=init&activity=2' + response.text[
                                                                                                                                               8:]
            # 打开新的请求页面
            else:
                deal_url = 'http://95598.sx.sgcc.com.cn' + response.text
            print(deal_url)
            # 打开表单处理页面
            html = webdriver.Chrome(r'./chromedriver.exe')
            html.get(deal_url)
            html.add_cookie({'name': 'logonUsername', 'value': u_name})
            html.add_cookie({'name': 'JSESSIONID', 'value': jsessionid['JSESSIONID']})
            html.refresh()
            # 页面跳转等待
            html.implicitly_wait(10)
            time.sleep(1)
            # 加载选项框,高压用电班选项
            script1 = """let sel = document.getElementsByName("flowHandleDept")[0];
                        sel.innerHTML = '<option value="0003025828">高压用电班</option>';
                      """
            html.execute_script(script1)

            # 选项框选择高压用电班
            # sel0 = html.find_element_by_name("flowHandleDept")
            # Select(sel0).select_by_value("0003025828")

            # 定位成农网标志下拉框
            sel = html.find_element_by_name("wkstHandle.gridFlag")
            # 选择用电
            Select(sel).select_by_value("01")
            # 定位下一步骤下拉框
            sel2 = html.find_element_by_name("forkValue")
            # 选择服务申请处理
            Select(sel2).select_by_value("服务申请处理")
            # 定位处理意见文本域
            html.find_element_by_name("handleOpinion").click()
            # 文本域输入内容
            html.find_element_by_name("handleOpinion").send_keys("夜间自动派单,白天重新整理!")
            # js注入进行保存/发送
            script = 'document.forms[0].submit()'
            html.execute_script(script)
            html.implicitly_wait(10)
            time.sleep(2)
            # 打印处理申请编号
            print("处理申请编号:" + str(app_no[0].text))
            # 保存处理的订单申请编号到log.txt
            with open('log.txt', 'a') as f:
                f.write(str(app_no[0].text) + '\n')
            # 关闭处理页浏览器窗口
            html.close()
    browser.close()


def main():
    current_path = os.getcwd()
    os.chdir(current_path)
    with open('log.txt', 'w') as f:
        pass
    while True:
        deal_task()
        time.sleep(60)


if __name__ == '__main__':
    main()

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值