方法一:使用Winform 的WebBorowser控件操控网页
page_load
{
webBrowser1.DocumentCompleted += WebBorowser1_DocumentCompleted;
//Load web
webBrowser1.Navigate("https://website/test.com");
}
private void WebBorowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Drawing.Rectangle screenSize = Screen.PrimaryScreen.Bounds;
webBrowser1.Width = screenSize.Width;
webBrowser1.Height =screenSize.Height;
// //webBrowser1.Width = webBrowser1.Document.Body.ScrollRectangle.Width;
// //webBrowser1.Height = webBrowser1.Document.Body.ScrollRectangle.Height;
HtmlElement element = webBrowser1.Document.GetElementsByTagName("a")[0];
if (element != null)
{
string elementContent = element.InnerText;
MessageBox.Show(elementContent);
}
else
{
MessageBox.Show("Not Found.");
}
//HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("input"); // 替换为你要查找的元素标签名 //foreach (HtmlElement element in elements)
// {
//if (element.GetAttribute("value") == "按钮的文本") // 替换为按钮的文本或其他属性
// {
//element.InvokeMember("click"); // 点击按钮 break;
//}
}
}
//截图保存
//private void SavePic()
//{
// Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height);
// webBrowser1.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, webBrowser1.Width, webBrowser1.Height));
// bitmap.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
// MessageBox.Show("Picture Save Done");
//}
方法二:使用Selenium操控网页
安装Selenium及对应浏览器驱动
using (var driver = new EdgeDriver())
{
driver.Navigate().GoToUrl("https://website/test.com");
driver.Manage().Window.Maximize();
//等待某元素出现并截图
//wait.Until(ExpectedConditions.ElementIsVisible(By.Id("lab1")));
//var screenshot=((ITakesScreenshot)driver).GetScreenshot();
//screenshot.SaveAsFile("test.png");
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2));
//等待直到标题出现
//wait.Until(d=>d.Title.Contains("Example Domain"));
//等待特定元素出现
wait.Until(d => d.FindElement(By.Id("lab1")).Displayed);
wait.Until(d => d.FindElement(By.Id("checkbox1")).Displayed);
wait.Until(d => d.FindElement(By.Id("btn1")).Displayed);
IWebElement checkbox = driver.FindElement(By.Id("checkbox1"));
//勾选框操作
if (checkbox.Selected == false)
{
checkbox.Click();
}
//查找按钮元素并点击
IWebElement buttonElement = driver.FindElement(By.Id("btn1"));
buttonElement.Click();
//wait.Until(d => d.FindElement(By.Id("btn_system")).Displayed);
//执行JavaScript脚本来滚动页面
//IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
//js.ExecuteScript("window.scrollTo(0,document.body.scrollHeight)");
//滚动到某个元素位置
//js.ExecuteScript("arguments[0].scrollIntoView(true);",targetElement);
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
}
catch
{
//....
}
}
版权归原作者 AI程序猿 所有, 如有侵权,请联系我们删除。