[VB/C#] Twitter にログイン

DevelopmentTwitter

コードから Twitter に スクリーンネームまたはメールアドレスとパスワードで、Twitter API を使わず、直接ログインして、HTML ページをダウンロードします。

下記コードの Login でログインし、必要な Cookie を取得します。ログイン後、例としてアカウント設定の HTML を取得しています。

System.Net, System.IO, System.Text, System.Text.RegularExpressions を import してください。

Visual Basic (VB.NET)

Sub Main()
' ログインして Cookie 取得
Dim cookies = Login("スクリーンネームまたはメールアドレス", "パスワード")
' 取得した Cookie を付けてアカウント設定ページにアクセス
Dim url = "https://twitter.com/settings/account"
Dim req = WebRequest.CreateHttp(New Uri(url))
req.CookieContainer = New CookieContainer
req.CookieContainer.Add(cookies)
Dim html As String
Using res = req.GetResponse
Using rs = res.GetResponseStream
Using sr = New StreamReader(rs)
html = sr.ReadToEnd
End Using
End Using
End Using
End Sub
Private Function GetAuthenticityTokenAndCookies() As Tuple(Of String, CookieCollection)
Dim req = WebRequest.CreateHttp("https://twitter.com/")
req.Method = "GET"
req.ServicePoint.Expect100Continue = False
req.CookieContainer = New CookieContainer
Using res = DirectCast(req.GetResponse, HttpWebResponse)
Dim html As String
Using rs = res.GetResponseStream
Using sr = New IO.StreamReader(rs, Encoding.UTF8)
html = sr.ReadToEnd
End Using
End Using
html = html.Substring(html.IndexOf("action=""https://twitter.com/sessions"""))
Dim m = Regex.Match(html, "value=""(?<token>.*?)""\s+name=""authenticity_token""")
Return New Tuple(Of String, CookieCollection)(m.Groups("token").Value, res.Cookies)
End Using
End Function
Private Function Login(name As String, password As String) As CookieCollection
Dim val = GetAuthenticityTokenAndCookies()
Dim token = val.Item1
Dim cookies = val.Item2
Dim param = String.Format("session%5Busername_or_email%5D={0}&session%5Bpassword%5D={1}&remember_me=0&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token={2}", name, password, token)
Dim buf = Text.Encoding.ASCII.GetBytes(param)
Dim uri = New Uri("https://twitter.com/sessions")
Dim req = WebRequest.CreateHttp(uri)
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
req.ContentLength = buf.Length
req.Referer = "https://twitter.com/"
req.ServicePoint.Expect100Continue = False
req.CookieContainer = New CookieContainer
If cookies IsNot Nothing Then
req.CookieContainer.Add(cookies)
End If
Using rs = req.GetRequestStream
rs.Write(buf, 0, buf.Length)
End Using
Dim html As String
Using res = req.GetResponse
Using rs = res.GetResponseStream
Using sr = New StreamReader(rs, Encoding.UTF8)
html = sr.ReadToEnd
End Using
End Using
Return req.CookieContainer.GetCookies(uri)
End Using
End Function

view raw
Module.vb
hosted with ❤ by GitHub

C#

static void Main(string[] args)
{
// ログインして Cookie 取得
var cookies = Login("スクリーンネームまたはメールアドレス", "パスワード");
// 取得した Cookie を付けてアカウント設定ページにアクセス
var url = "https://twitter.com/settings/account";
var req = WebRequest.CreateHttp(new Uri(url));
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookies);
string html = null;
using (var res = req.GetResponse())
{
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs))
{
html = sr.ReadToEnd();
}
}
}
}
private static Tuple<string, CookieCollection> GetAuthenticityTokenAndCookies()
{
var req = WebRequest.CreateHttp("https://twitter.com/");
req.Method = "GET";
req.ServicePoint.Expect100Continue = false;
req.CookieContainer = new CookieContainer();
using (var res = req.GetResponse() as HttpWebResponse)
{
string html = null;
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
}
html = html.Substring(html.IndexOf("action=\"https://twitter.com/sessions\""));
var m = Regex.Match(html, "value=\"(?<token>.*?)\"\\s+name=\"authenticity_token\"");
return new Tuple<string, CookieCollection>(m.Groups["token"].Value, res.Cookies);
}
}
private static CookieCollection Login(string name, string password)
{
var val = GetAuthenticityTokenAndCookies();
var token = val.Item1;
var cookies = val.Item2;
var param = string.Format("session%5Busername_or_email%5D={0}&session%5Bpassword%5D={1}&remember_me=0&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token={2}", name, password, token);
var buf = System.Text.Encoding.ASCII.GetBytes(param);
var uri = new Uri("https://twitter.com/sessions");
var req = WebRequest.CreateHttp(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = buf.Length;
req.Referer = "https://twitter.com/";
req.ServicePoint.Expect100Continue = false;
req.CookieContainer = new CookieContainer();
if (cookies != null)
{
req.CookieContainer.Add(cookies);
}
using (var rs = req.GetRequestStream())
{
rs.Write(buf, 0, buf.Length);
}
string html = null;
using (var res = req.GetResponse())
{
using (var rs = res.GetResponseStream())
{
using (var sr = new StreamReader(rs, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
}
return req.CookieContainer.GetCookies(uri);
}
}

view raw
Program.cs
hosted with ❤ by GitHub