3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

既に開いているEdgeを、WebDriverで操作する(C#)

Posted at

ブラウザ操作の自動化をしたい、と言っても、ブラウザを開く初手からすべて自動化するのは、それはそれでかったるい。ある程度、手でブラウザをたどった後に、部分的に処理を自動化したい、という場面の方が多い。その場合、既に開いてあるEdgeを、拾って、自動操作する、ということがやりたい。

必要なのは2点。

その1:Egde起動時に2つの指定

コマンドプロンプトから
--remote-debugging-port
--user-data-dir
を指定してEdgeを起動する。(そして、そのEgdeで望む手動操作をしておく)

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --remote-debugging-port=9222 --user-data-dir="C:\myTestEdgeProfile" "www.yahoo.co.jp"

その2:ソース中、オプション指定

EdgeDriveを生成する際のOptionにて、DebuggerAddress を指定する

var options = new EdgeOptions();
options.DebuggerAddress = "127.0.0.1:9222";
var driver = new EdgeDriver(options);

ソース

EdgeDriver_2.cs
//c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:WebDriver.dll /target:exe EdgeDriver_2.cs

using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using System.Threading;

namespace EdgeDriver_2
{
	class Program
	{
		static void Main(string[] args)
		{
			var options = new EdgeOptions();
			options.DebuggerAddress = "127.0.0.1:9222";
			var driver = new EdgeDriver(options);
			try
			{
				//driver.Url = "https://www.yahoo.co.jp";
				var elements = driver.FindElements(By.XPath("//DIV/H1/SPAN"));
				foreach (var e in elements){
					System.Console.WriteLine("-> " + (e.Text));
				}
			}
			finally
			{
				//driver.Quit();
			}
		}
	}
}

実行画面

image.png

image.png

image.png

参考

3
8
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?