c# selenium element screenshot

Install components via NuGet

Install Selenium.WebDriver, Selenium.Support, Selenium.RC selected in the picture

NuGet download selenium components

Open the web page and find the element to take a screenshot of the element

ps: Before writing the code, you need to confirm whether chromedriver.exe exists or not, and you need to confirm whether the version is consistent with Google Chrome == (this is a pit, don't step on it) ==

Only By.XPath(""); is used here, a / represents the root element. It is not recommended to use it here. If you need to use it, it is best to use the XPathHelper plug-in to better determine the element.
Here is Baidu as an example, directly upload the code, there are comments in the code for easy viewing.
Requirements: Get the button of Baidu and save the screenshot locally
Requirements page

	
	
	string url="http://www.baidu.com";	
	IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver();//打开谷歌浏览器
	driver.Navigate().GoToUrl(url);//跳转到百度页面
	var baiduElement=driver.FindElement(By.XPath("//span[@class='btn_wr s_btn_wr bg']"));//查找百度一下的元素
	Screenshot screenshot = ((ITakesScreenshot)image).GetScreenshot();//对百度一下这个按钮进行截图
	//保存图片
	var dirpath = @"D:\image";
    if (!Directory.Exists(dirpath))
            {
    
    
                Directory.CreateDirectory(dirpath);
            }
            screenshot.SaveAsFile(@"D:\code\code.png", ScreenshotImageFormat.Png);//保存图片
            if (File.Exists(@"D:\code\code.png")) 
            {
    
    
                Image img = Image.FromFile(@"D:\image\baidu.png");               
            } 

Guess you like

Origin blog.csdn.net/weixin_43474597/article/details/114136427
Recommended