7
13

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.

C#でSeleniumのTips

Last updated at Posted at 2021-03-22

よく使うC#のSeleniumについてメモ書きします。

参照

hoge.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;

chromeドライバーのお作法

hoge.cs

        private void Form1_Load(object sender, EventArgs e)
        {
               //ChromeDriverを設定する
                ChromeDriver driver = Selenium();

                // URLに移動します。
                driver.Navigate().GoToUrl(@"https://zozo.jp/");

                //Chromeドライバー終了処理
                SeleniumEnd(driver);
        }

#region ChromeDriver設定
        private ChromeDriver Selenium()
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();
            var options = new ChromeOptions();

            //ブラウザ非表示
            if (CB_ChromeDisp.Checked == false)
            {
                service.HideCommandPromptWindow = true;

                options.AddArgument("--headless");
                options.AddArgument("--no-sandbox");
                options.AddArgument("--window-position=-32000,-32000");
                options.AddArgument("--user-agent=hogehoge");
            }

            ChromeDriver driver = new ChromeDriver(service, options);

            return driver;

        }

#endregion

#region ChromeDriver終了処理
        private void SeleniumEnd(ChromeDriver driver)
        {
            driver.Quit();
        }

#endregion

色々な操作の仕方

hoge.cs

IWebElement element = driver.FindElement(By.Id("btnNext"));
IWebElement element = driver.FindElement(By.XPath("hogehoge"));
IWebElement element = driver.FindElement(By.ClassName("CheckExpand__label"));
IWebElement element = driver.FindElement(By.Name("Description_plain_work"));

//GetAttributeで要素の指定された属性の値を取得する
IWebElement element = driver.FindElement(By.ClassName("CheckExpand__label")).GetAttribute("data-selected-price");
IWebElement element = driver.GetAttribute("data-selected-price");


//複数取得してループで回す処理
List<IWebElement> elements = driver.FindElements(By.ClassName("p-goods-add-cart__color")).ToList();
foreach (IWebElement ele in elements)
    {
        Console.WriteLine(ele.Text);
    }

//チェックボックスを選択する場合はSpaceを送る
IWebElement element=driver.FindElement(By.ClassName("CheckExpand__label"));
element.SendKeys(OpenQA.Selenium.Keys.Space);

//ドロップダウン
IWebElement element = driver.FindElement(By.Name("istatus"));
var selectElement = new SelectElement(element);
selectElement.SelectByIndex(3);

//クリックは.Click()では動作しない場合もある
element=driver.FindElement(By.Id("aucHTMLtag"));
element.SendKeys(OpenQA.Selenium.Keys.Return);//もしくはKeys.Enter

hoge.cs

List<IWebElement> elements = driver.FindElements(By.CssSelector("#list01 h3")).ToList();


//URLリストを定義する
List<string> url_list = new List<string>();

// 記事のタイトルをコンソールに表示
foreach (IWebElement ele in elements)
    {
        //url
        lsc_yoku_listdata_rec.Yoku_itemurl = ele.FindElements(By.TagName("a"))[0].GetAttribute("href");

        //Console.WriteLine(lsc_yoku_listdata_rec.Yoku_itemurl);         // アドレス

        //urlを配列に代入する
        url_list.Add(lsc_yoku_listdata_rec.Yoku_itemurl);

    }

//リストを配列に載せ替える
url_arr = url_list.ToArray();

//配列のカウント
url_count = url_arr.Count();

//カウント
int i = 0;

//URLを取出して個別ページの処理を行う
foreach (string url in url_arr)
{
// ループ処理の途中にキャンセルされたかを確認する
if (MainBackgroundWorker.CancellationPending)
{
//キャンセルされてた場合の処理
e.Cancel = true;
return;
}

lsc_yoku_listdata_rec.Yoku_itemurl = url;

driver.Navigate().GoToUrl(url);

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3);

//5秒間停止する
System.Threading.Thread.Sleep(5000);


// htmlファイルを読み込む
//var html = File.ReadAllText(driver.PageSource, System.Text.Encoding.UTF8);

// HTMLParserのインスタンス生成
var parser = new HtmlParser();

// htmlをパースする
var doc = parser.ParseDocument(driver.PageSource);

// idを指定してElement取得
var detail_element = doc.GetElementById("pageTop");

item_detail(detail_element);

i++;

// マルチスレット対応してテキストボックスを操作
Invoke(new Action<string>(status_mess), i +" / "+ url_count+ "件取得済み");

}

hoge.cs
            //詳細
            List<IWebElement> details = driver.FindElements(By.ClassName("p-goods-information-action")).ToList();

            int flg = 0;

            foreach (IWebElement detail in details)
            {
                string url_price = "";
                string url_size = "";
                string url_color = "";
                string url_name = "";
                string url_zaiko = "";


                url_color = detail.FindElement(By.ClassName("p-goods-add-cart__color")).Text.Replace(" ", "");
                url_size = detail.FindElements(By.TagName("span"))[2].Text.Replace("/", "").Replace(" ", ""); 


                if (url_color == cell_color && url_size == cell_size)
                {
                    //見つかったときはフラグ:1
                    flg = 1;

                    url_zaiko = detail.FindElements(By.TagName("span"))[3].Text;
                    url_name = driver.FindElement(By.ClassName("p-goods-information__heading")).Text.Replace(" ", "");

                    try
                    {
                        url_price = driver.FindElement(By.ClassName("p-goods-information__price")).Text.Replace(@"\", "").Replace(@",", "").Replace(" ", "");
                    }
                    catch
                    {
                        url_price = driver.FindElement(By.ClassName("p-goods-information__price--discount")).Text.Replace(@"\", "").Replace(@",", "").Replace(" ", "");
                    }

                    cell_price = url_price;
                    cell_color = url_color;
                    cell_name = url_name;
                    cell_zaiko = url_zaiko;

                    //セルに値を入れる
                    worksheet.Cell(i, 6).Value = cell_name;
                    worksheet.Cell(i, 16).Value = cell_zaiko;
                    worksheet.Cell(i, 9).Value = cell_price;
                    worksheet.Cell(i, 7).Value = cell_color;

                    worksheet.Cell(i, 16).Style.Fill.BackgroundColor = XLColor.White;
                }
            }

Captchaを突破する方法

image.png

7
13
0

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
7
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?