使用Selenium+ChromeDriver登录微博并且获取cookie

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;



   public class GetSinaCookie { private static string userName = "name"; private static string paw = "passward"; public static void RefreshCookie() { // https://weibo.com var url = "https://weibo.com"; var driver = new ChromeDriver(); driver.Navigate().GoToUrl(url); Thread.Sleep(15 * 1000); var btn = driver.FindElement(By.XPath("//a[@node-type='loginBtn']")); btn.Click(); Thread.Sleep(10 * 1000); var temp = driver.FindElements(By.XPath("//a[@node-type='submitBtn']")); var oun = temp.Count(); var userNameinput = driver.FindElement(By.XPath("//input[(@node-type='username') and (@tabindex = '3')]")); var pawInput = driver.FindElements(By.XPath("//input[(@name='password')]")).ToArray()[2]; //driver.FindElement(By.XPath("//input[(@name='password')]")); var loginbtn = driver.FindElements(By.XPath("//a[@node-type='submitBtn']")).ToArray()[2]; userNameinput.SendKeys(userName); Thread.Sleep(5 * 1000); pawInput.SendKeys(paw); loginbtn.Click();
       Thread.Sleep(2 * 1000);
       var dd = driver.Manage().Cookies.AllCookies.ToDictionary(cookie => cookie.Name, cookie => cookie.Value); StringBuilder strBuilder = new StringBuilder(); foreach (var d in dd) { var line = d.Key + "=" + d.Value + "; "; strBuilder.Append(line); } var cookieStr = strBuilder.ToString().Trim(); cookieStr = cookieStr.Substring(0, cookieStr.Length - 1); driver.Close(); driver.Quit(); } }

 注意点:

1、在获取节点前、点击按钮前、点击按钮后、以及获取cookie前的操作,要暂停一下,比如暂停2到3秒,防止节点或者页面没有加载完成导致无法获取节点或者给节点赋值不正确等错误

2、以上代码仅适用于不需要输入验证码的情况。

 

posted @ 2019-01-25 17:15  向萧  阅读(2387)  评论(0编辑  收藏  举报