To programmatically log in to Weibo (weibo.com) and extract session cookies using Selenium with ChromeDriver in C#, follow the implementation below. This approach assumes no CAPTCHA or two-factor authentication is triggered during login.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
public class WeiboCookieExtractor
{
private static readonly string Username = "your_username";
private static readonly string Password = "your_password";
public static string RetrieveCookies()
{
var options = new ChromeOptions();
// Optional: run headless for background execution
// options.AddArgument("--headless");
using var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://weibo.com");
// Wait for initial page load
Thread.Sleep(15000);
// Click the login button
var loginTrigger = driver.FindElement(By.XPath("//a[@node-type='loginBtn']"));
loginTrigger.Click();
Thread.Sleep(10000);
// Locate username and password fields
var usernameField = driver.FindElement(By.XPath("//input[@node-type='username' and @tabindex='3']"));
var passwordFields = driver.FindElements(By.XPath("//input[@name='password']"));
var passwordField = passwordFields[2]; // Target the correct password input
// Enter credentials
usernameField.SendKeys(Username);
Thread.Sleep(5000);
passwordField.SendKeys(Password);
// Submit login form
var submitButtons = driver.FindElements(By.XPath("//a[@node-type='submitBtn']"));
var submitButton = submitButtons[2];
submitButton.Click();
// Allow time for post-login redirect and cookie setting
Thread.Sleep(5000);
// Extract all cookies as a dictionary
var cookies = driver.Manage().Cookies.AllCookies;
var cookieDict = new Dictionary<string, string>();
foreach (var cookie in cookies)
{
cookieDict[cookie.Name] = cookie.Value;
}
// Format as cookie header string (e.g., "key1=value1; key2=value2")
var builder = new StringBuilder();
foreach (var kvp in cookieDict)
{
builder.Append($"{kvp.Key}={kvp.Value}; ");
}
var cookieString = builder.ToString().TrimEnd(' ', ';');
return cookieString;
}
}
Key Considerations:
- Introduce deliberate delays (
Thread.Sleep) before interacting with elements or extracting cookies to ensure the DOM and resources have fully loaded. - This method only works when Weibo does not require solving a CAPTCHA or completing additional verification steps.
- For production use, conisder replacing fixed sleep durations with explicit waits (e.g.,
WebDriverWait) for better reliability.