影刀RPA 网页长截图与区域截图的多种姿势
影刀RPA 网页长截图与区域截图的多种姿势作者林焱什么情况用这个影刀内置的截图功能只能截可视区域但业务上经常需要截整页比如截取完整的订单详情保留证据、截取特定区域只截表格不截导航栏、或者把一长串页面拼成一张图。这篇文章覆盖网页截图的所有常见需求每种场景都给你直接能用的代码。怎么做拼多多店群自动化上架方案全页截图deffull_page_screenshot(driver,output_path):截取完整页面包括需要滚动才能看到的部分# 获取页面总高度total_heightdriver.execute_script(return document.body.scrollHeight)viewport_heightdriver.execute_script(return window.innerHeight)# 设置窗口大小为全页高度driver.set_window_size(1920,total_height)time.sleep(0.5)# 截图driver.save_screenshot(output_path)# 恢复窗口driver.set_window_size(1920,viewport_height)元素截图defelement_screenshot(driver,element_selector,output_path):截取指定元素区域elementdriver.find_element(By.CSS_SELECTOR,element_selector)element.screenshot(output_path)拼接长图fromPILimportImageimportiodefscroll_and_stitch_screenshot(driver,output_path,overlap50):滚动截取并拼接——适用于超长页面total_heightdriver.execute_script(return document.body.scrollHeight)viewport_heightdriver.execute_script(return window.innerHeight)screenshots[]current_scroll0whilecurrent_scrolltotal_height:driver.execute_script(fwindow.scrollTo(0,{current_scroll});)time.sleep(0.3)screenshotdriver.get_screenshot_as_png()screenshots.append(Image.open(io.BytesIO(screenshot)))current_scrollviewport_height-overlap# 拼接total_widthscreenshots[0].width total_height_combinedsum(img.heightforimginscreenshots)-overlap*(len(screenshots)-1)combinedImage.new(RGB,(total_width,total_height_combined))y_offset0forimginscreenshots:combined.paste(img,(0,y_offset))y_offsetimg.height-overlap combined.save(output_path)区域截图边框标注截取特定区域并在上面画框标注fromPILimportImageDrawdefscreenshot_with_highlight(driver,element_selector,output_path):截取区域并用红框标注elementdriver.find_element(By.CSS_SELECTOR,element_selector)locationelement.location sizeelement.size screenshotImage.open(io.BytesIO(driver.get_screenshot_as_png()))drawImageDraw.Draw(screenshot)# 画红框x,ylocation[x],location[y]draw.rectangle([x,y,xsize[width],ysize[height]],outlinered,width3)screenshot.save(output_path)有什么坑坑一全页截图中fixed元素重复出现TEMU店群如何管理运营现象拼接长图时导航栏等fixed定位的元素出现在每一段截图中。解决截图前用JS临时隐藏fixed元素截图后恢复。坑二Canvas内容截不到现象页面上的图表Canvas渲染在截图中显示为空白。解决用Canvas的toDataURL()方法转换后再截或者用浏览器级别的截图CDP。坑三截图文件太大现象全页截图动辄几十MB每天截几十张磁盘受不了。解决降低分辨率和压缩质量或者转JPEG格式。总结截图选择——只要可视区域 →save_screenshot()只要某个元素 →element.screenshot()要完整页面 → 拼接或调整窗口法要标注 → PIL绘制。