python 操作selenium 每日自动写禅道日报

1.安装selenium

pip install selenium

2.下载chromedriver

地址1:http://chromedriver.storage.googleapis.com/index.html

(下载安装的浏览器对应的版本)

from selenium import webdriver
import time 
import datetime
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys

#登录账号
account=""
#登录密码
password=""
#登录页
login=""
#日报页
dailyPaper=""
#日志模板
formwork=""
#周报日期
week=""
#任务类型
tastType=""
#指定发送
specifySend=""
f = open("config.env","r",encoding='utf-8')  #可读可写二进制,文件若不存在就创建
for line in f.readlines():#行读取
    if line.find("account")>0:
       account=line.split("=")[1].replace(" ","")
    if line.find("password")>0:
       password=line.split("=")[1].replace(" ","")
    if line.find("login")>0:
       login=line.split("=")[1].replace(" ","")
    if line.find("dailyPaper")>0:
       dailyPaper=line.split("=")[1].replace(" ","")       
    if line.find("formwork")>0:
       formwork=line.split("=")[1].replace(" ","")
    if line.find("week")>0:
       week=line.split("=")[1].replace(" ","")
    if line.find("tastType")>0:
       tastType=line.split("=")[1].replace(" ","")
    if line.find("specifySend")>0:
       specifySend=line.split("=")[1].replace(" ","")  


# 如果driver添加了环境变量则不需要设置executable_path
# 实例化ChromeOptions
options = webdriver.ChromeOptions()
# 关闭浏览器提示信息
options.add_argument('disable-infobars')
# 关闭浏览器提示信息
options.add_experimental_option("excludeSwitches", ['enable-automation','enable-logging'])
options.add_experimental_option("useAutomationExtension", False)
# 浏览器全屏
#options.add_argument('start-fullscreen')
# 忽略ssl错误
options.add_argument('--ignore-ssl-error')
#不自动关闭浏览器
options.add_experimental_option('detach', True) 
#浏览器窗口最大化
#options.add_argument('--start-maximized')
# 如果driver没有添加到了环境变量,则需要将driver的绝对路径赋值给executable_path参数
driver = webdriver.Chrome(options=options,executable_path='H:/chromedriver_win32/chromedriver.exe')
# 向一个url发起请求
driver.get(login)

# 把网页保存为图片,69版本以上的谷歌浏览器将无法使用截图功能
# driver.save_screenshot("itcast.png")
print(driver.title) # 打印页面的标题
def find(type="xpath",value="",remark=""):
    while (True):
        findxpa=driver.find_elements(type,value)
        if(len(findxpa)<=0):
            print("查找find %s ...%s"%(len(findxpa),remark))
            continue
        else:
            print("找到find %s ...%s"%(len(findxpa),remark))
            return findxpa[0]
def iframeFind(type="xpath",iframeVale="",value="",remark=""):
    while (True):
        f=find("xpath",iframeVale,"iframe"+remark)
        driver.switch_to.frame(f)
        findxpa=driver.find_elements(type,value)
        if(len(findxpa)<=0):
            print("查找iframeFind %s ...%s"%(len(findxpa),remark))
            continue
        else:
            print("找到iframeFind %s ...%s"%(len(findxpa),remark))
            return findxpa[0]  
def last_day_of_month(any_day):
    """
    获取获得一个月中的最后一天
    :param any_day: 任意日期
    :return: string
    """
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)
f=find("xpath",'//*[@id="account"]',"账号")
f.send_keys('zhangst')
f=find("xpath",'//*[@id="loginPanel"]/div/div[2]/form/table/tbody/tr[2]/td/input',"密码")
f.send_keys('zhang123456')
f=find("xpath",'//*[@id="submit"]',"登录")
f.click()
time.sleep(1)

# driver.get("http://47.104.97.246:81/zentao/execution-task-73.html?tid=tbjb59jk")
# f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="mainMenu"]/div[3]/div[3]/a',"新建")
# f.click()
# driver.switch_to.default_content()

driver.get(dailyPaper)


#------------------------------------------------------------------------------------------------
f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="dataform"]/table/tbody/tr[4]/td[1]',"点击任务类型")
f.click()
driver.switch_to.default_content()
f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="type_chosen"]/div/ul/li['+str(tastType)+']',"选择任务类型")
f.click()
driver.switch_to.default_content()
#------------------------------------------------------------------------------------------------
f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="dataPlanGroup"]',"点击指派给")
f.click()
driver.switch_to.default_content()
f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="assignedTo_chosen"]/div/ul/li['+str(specifySend)+']',"选择指派给")
f.click()
driver.switch_to.default_content()
#------------------------------------------------------------------------------------------------

f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="name"]',"任务名称")
title="日报"
# 当前日期
now = datetime.datetime.now().date()
year,month,day = str(now).split("-")  # 切割
# 年月日,转换为数字
year = int(year)
month = int(month)
day = int(day)
# 获取这个月最后一天
last_day = last_day_of_month(datetime.date(year, month, day))
# 判断当前日期是否为月末
if str(now) == last_day:
    title="月报"
else:
    if datetime.datetime.now().weekday()==int(week)-1:
        title="周报"
f.send_keys(time.strftime('%Y-%m-%d',time.localtime(time.time()))+title)
driver.switch_to.default_content()
#先找第一层
f=iframeFind("xpath",'//*[@id="appIframe-project"]','//*[@id="name"]',"任务描述外层")
#在找第二层
f=iframeFind("xpath",'//*[@id="dataform"]/table/tbody/tr[11]/td/div[3]/div[2]/iframe','/html/body',"任务描述内层")
f.click()
content=""
for part in formwork.split('\\n'):
    content+=part+"\n"
f.send_keys(content)
driver.switch_to.default_content()



# 退出模拟浏览器
#driver.quit() # 一定要退出!不退出会有残留进程!

ENV

[config]
    #登录账号
    account=123456
    #登录密码
    password=123456
    #登录页
    login=http://127.0.0.1/zentao/user-login.html?tid=tbjb59jk
    #日报页
    dailyPaper=http://127.0.0.1/zentao/task-create-73-0-0.html?tid=tbjb59jk
    #日志模板
    formwork=昨日已完成:\n1. 无\n今日计划:\n 1. 无\n其他问题\n 1. 无
    #周报日期
    week=6
    #任务类型
    tastType=2
    #指定发送
    specifySend=1


options.add_argument('--disable-infobars')  # 禁止策略化
options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
options.add_argument('--incognito')  # 隐身模式(无痕模式)
options.add_argument('--disable-javascript')  # 禁用javascript
options.add_argument('--start-maximized')  # 最大化运行(全屏窗口),不设置,取元素会报错
options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
options.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置
options.add_argument('lang=en_US') # 设置语言
options.add_argument('User-Agent=Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36')
options.add_argument('--headless')  # 浏览器不提供可视化页面
prefs = {"":""}
prefs["credentials_enable_service"] = False
prefs["profile.password_manager_enabled"] = False
chrome_option_set.add_experimental_option("prefs", prefs) # 屏蔽'保存密码'提示框



find_element_by_id                      (返回一个元素)
find_element(s)_by_class_name           (根据类名获取元素列表)
find_element(s)_by_name                 (根据标签的name属性值返回包含标签对象元素的列表)
find_element(s)_by_xpath                (返回一个包含元素的列表)
find_element(s)_by_link_text            (根据连接文本获取元素列表)
find_element(s)_by_partial_link_text    (根据链接包含的文本获取元素列表)
find_element(s)_by_tag_name             (根据标签名获取元素列表)
find_element(s)_by_css_selector         (根据css选择器来获取元素列表)


find_element_by_xpath('//*[@id=""]')等同于find_element_by_id("")
find_element_by_xpath('//*[@name=""]')等同于find_element_by_name("")
find_element_by_xpath('//*[@class=""]')等同于find_element_by_class_name("")
find_element_by_xpath('//标签名')等同于find_element_by_tag_name("标签名")
find_element_by_xpath('//a[contains(text(),"")]')等同于find_element_by_link_text("")
find_element_by_xpath('//*[@id=""]')等同于find_element_by_partial_link_text("")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值