这里写自定义目录标题
- 使用场景
- 准备环境
- 实现逻辑
- 引入包
- 截图模块
- 访问mysql数据库,获取标题和网址
- 截图并保存为word
使用场景
从mysql数据库中读取需求标题和对应网页传参,提供网页截图,将截图放入word文档中,并添加上对应标题。
准备环境
1、pycharm
2、具备mysql库
3、支持pytharm打开google浏览器(配置chromedriver.exe,可参考[https://blog.csdn.net/xmh1998/article/details/104069592])
实现逻辑
引入包
import time
import win32gui, win32ui, win32con, win32api
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import pymysql
import random
from docx import Document
from docx.shared import Inches
import shutil
import subprocess
from retrying import retrydef retry_error(exception):time.sleep(20)return isinstance(exception, NameError)# return isinstance(exception, Exception)
截图模块
@retry(retry_on_exception=retry_error, stop_max_attempt_number=3)
def window_capture(filename):hwnd = 0 # 窗口的编号,0号表示当前活跃窗口# 根据窗口句柄获取窗口的设备上下文DC(Divice Context)hwndDC = win32gui.GetWindowDC(hwnd)# 根据窗口的DC获取mfcDCmfcDC = win32ui.CreateDCFromHandle(hwndDC)# mfcDC创建可兼容的DCsaveDC = mfcDC.CreateCompatibleDC()# 创建bigmap准备保存图片saveBitMap = win32ui.CreateBitmap()# 获取监控器信息MoniterDev = win32api.EnumDisplayMonitors(None, None)w = random.randint(1100, 1300)h = random.randint(147, 151)# w = random.randint(1000, 1400)# h = random.randint(280, 290)# print(w,h)# 为bitmap开辟空间saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)# 高度saveDC,将截图保存到saveBitmap中saveDC.SelectObject(saveBitMap)# 截取从左上角(0,0)长宽为(w,h)的图片saveDC.BitBlt((0, -195), (1440, 900), mfcDC, (0, 0), win32con.SRCCOPY)# saveDC.BitBlt((-30, -160), (1440, 900), mfcDC, (0, 0), win32con.SRCCOPY)saveBitMap.SaveBitmapFile(saveDC, filename)
访问mysql数据库,获取标题和网址
def mysql_conn():#链接mysqlconn = pymysql.connect(host='192.168.0.103', port=3306, user='root', passwd='xxxx', db='aaaa')cursor = conn.cursor()cursor.execute("select distinct table_name from biaotou")# conn.commit()tablename = cursor.fetchall()cursor.close()conn.close()print(tablename)listdate = []for row in tablename:listdate.append(row[0])return listdate
截图并保存为word
if __name__ == "__main__":#生成功能点列表listdate=mysql_conn()# 创建浏览器对象chrome_options = Options()# 关闭使用 ChromeDriver 打开浏览器时上部提示语 "Chrome正在受到自动软件的控制"chrome_options.add_argument("disable-infobars")# 打开docx文件document = Document('D:/xxx/aaaa.docx')#循环生成报表链接for aa in listdate:url = str(aa)print(url)#调用浏览器服务driver = webdriver.Chrome()#窗口最大化driver.maximize_window()#打开地址driver.get(url)#因数据显示慢,随眠1秒time.sleep(1)#截图保存window_capture("D:/xxx/"+aa+".jpg")#退出浏览器driver.quit()#创建新段落pl = document.add_paragraph()#添加标题document.add_heading(aa, level = 2)#添加正文# run1 = pl.add_run('xxxx' )# run1.font.name = '微软雅黑'# run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')# run1.font.size = Pt(21)# 是否加粗# run1.font.bold = True#想docx中插入图片document.add_picture("D:/xxx/"+aa+".jpg", width=Inches(6))pl = document.add_paragraph()document.save("D:/xxx/aaaa.docx")