You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium中获取指定两个元素/定位器之间的单张截图?

如何截取两个Web元素之间的区域截图

你的代码中的问题

  • 重复查找相同元素,无端增加执行时间
  • 坐标与尺寸计算逻辑错误:
    • int x = Math.Min(LocationTwo.X, LocationTwo.X); 错误使用同一元素的X坐标,应取两个元素X的最小值
    • Width 计算时用两次LocationTwo.X相减,结果恒为0,且错误叠加最大宽度
    • Height 计算时错误使用元素的Size.Width而非Size.Height,坐标差计算同样出错
  • 滥用Thread.Sleep,建议改用显式等待保证元素加载完成

修正后的实现代码

// 1. 仅查找一次目标元素
IWebElement ApplicantOne = driver.FindElement(By.XPath("//div/div[1]/table/tbody/tr/td[3]/span"));
IWebElement ApplicantTwo = driver.FindElement(By.XPath("//div/div[11]/table/tbody/tr/td[3]/span"));

// 2. 获取元素的位置与尺寸信息
Point loc1 = ApplicantOne.Location;
Size size1 = ApplicantOne.Size;
Point loc2 = ApplicantTwo.Location;
Size size2 = ApplicantTwo.Size;

// 3. 计算截取区域的左上角坐标和宽高
int cropX = Math.Min(loc1.X, loc2.X);
int cropY = Math.Min(loc1.Y, loc2.Y);
int cropWidth = Math.Max(loc1.X + size1.Width, loc2.X + size2.Width) - cropX;
int cropHeight = Math.Max(loc1.Y + size1.Height, loc2.Y + size2.Height) - cropY;

// 4. 截取全屏并裁剪目标区域
Screenshot fullScreenshot = ((ITakesScreenshot)driver).GetScreenshot();
Bitmap originalBitmap = (Bitmap)new ImageConverter().ConvertFrom(fullScreenshot.AsByteArray);
Bitmap croppedBitmap = originalBitmap.Clone(new Rectangle(cropX, cropY, cropWidth, cropHeight), originalBitmap.PixelFormat);

// 5. 保存截图
croppedBitmap.Save(@"C:\Users\DCOHLO34\Desktop\Themes\ScreenShot.png", System.Drawing.Imaging.ImageFormat.Png);

额外优化建议

  • 替换Thread.Sleep为显式等待,确保元素可被定位:
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    IWebElement ApplicantOne = wait.Until(d => d.FindElement(By.XPath("//div/div[1]/table/tbody/tr/td[3]/span")));
    
  • 如果元素在滚动区域内,先滚动到元素可见位置,避免截图偏移:
    ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", ApplicantOne);
    

内容的提问来源于stack exchange,提问作者sivaguru y v

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 06:35:30