之前说到可爱猫+python3+Flask+aiohttp简单搭建微信机器人
每日都要进行重复性的安全设备巡检,比较麻烦,简单的头脑风暴一下,利用selenium进行对安全设备的自动化巡检并返回相关截图
前提准备:
pip install selenium(python3)
或者
pip install msedge.selenium_tools(python3)
pip install PIL (python3)
msedgedriver: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
或者
Chromedriver:自行百度
达成效果如图
主要代码如下
from msedge.selenium_tools import Edge,EdgeOptions
from PIL import Image,ImageDraw,ImageFont
import time,os
def screetshot_1():
edgeDriverPath = r'..\msedgedriver.exe'
#无头模式
options = EdgeOptions()
options.use_chromium =True
options.add_argument('ignore-certificate-errors')
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument("--inprivate")
#设置网页大小为1920*1080
options.add_argument('--window-size=1920,1050')
driver = Edge(executable_path=edgeDriverPath, options=options)
url = '...'
driver.get(url)
#等待加载动画
time.sleep(5)
#输入账号 登录框的xpath1
driver.find_element_by_xpath(xpath1).send_keys('admin')
#输入密码 登录框的xpath2
driver.find_element_by_xpath(xpath2).send_keys('pass')
#点击 按钮的xpath3
driver.find_element_by_xpath(xpath3).click()
#等待网页加载完毕
driver.implicitly_wait(5)
url = driver.current_url
driver.quit()
time.sleep(3)
#截图
driver.save_screenshot('img.png')
#给图片下方添加一个高度30的白色背景
img = Image.open('img.png')
width,height = img.size
new_img = Image.new('RGB',(width,height+30),(255,255,255))
new_img.paste(img,(0,0,width,height))
#在图片下方添加文字'Create By @一键巡检Bot'
draw = ImageDraw.Draw(new_img)
font = ImageFont.truetype(r'C:\Windows\Fonts\simhei.ttf',20)
nowtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
draw.text((10,height+5),f'Create By @一键巡检Bot,From Page:{url},Check time:{nowtime}',fill=(0,0,0),font=font)
#返回图片完整地址
new_img.save('img.png')
return 'img.png'
然后导入微信机器人主函数中
...
from plugin.yijianxunjian import screetshot_1
from httpapi import send_msg_group,send_image_msg
...
if "#巡检安全设备" in msg and msg_type == '200': # type: ignore
args = msg.split('巡检态势感知')[-1]
starttime = time.time()
await send_msg_group('正在巡检态势感知,耗时约15秒,请稍候...',from_wxid) # type: ignore
if args == '':
#发送图片
picpath = f'D:\pythonconda\wechatbot\{screetshot_1()}' # type: ignore
endtime = time.time()
#用时 取两位小数
usetime = round(endtime-starttime,2)
await send_msg_group(f'巡检完成,用时{usetime}秒',from_wxid) # type: ignore
await send_image_msg(picpath,from_wxid)
return 'ok'
#其中send_image_msg主要如下,写到httpapi.py就行
async def send_image_msg(picpath, to_wxid):
data = {
"type": "103",
"msg": picpath,
"to_wxid": to_wxid,
"robot_wxid":"wxid_xxxxxx"
}
data = json.dumps(data)
async with aiohttp.ClientSession() as session:
async with session.post(url, data=data) as resp:
print(await resp.text())