我已经完成此代码来登录、检索和显示网页:
// login info array
string postData = "user_name=tler";
postData += "&user_password=lodvader";
byte[] data = Encoding.ASCII.GetBytes(postData);
// web request
WebRequest req = WebRequest.Create("http://www.lol.com/login.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// stream response to string
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("iso-8859-1"));
string responseString = reader.ReadToEnd();
// retrieve text within title
Regex rx = new Regex(@"(?<=<title>).+?(?=</title>)");
var variable = rx.Matches(responseString);
// output
Console.WriteLine(variable[0]);
Console.ReadLine();
但是,登录后的以下页面是一个 html 重定向,如下所示:
<meta http-equiv="refresh" content="3; URL="bb.php">
如何点击此链接并检索下一页?
最佳答案
只需向 bb.php 文件发送一个新的 WebRequest。确保您使用相同的 CookieContainer,因为我认为 login.php 使用基于 cookie 的 session 来记住您。查看HttpWebRequest.CookieContainer属性(property)。这需要您将 WebRequest 转换为 HttpWebRequest。
添加:(无法在评论中编写示例代码。)
我只是在编写代码,现在还没有校对...
var cookies = new CookieContainer();
var firstReq = (HttpWebRequest)WebRequest.Create(".../login.php");
firstReq.CookieContainer = cookies;
var secondReq = (HttpWebRequest)WebRequest.Create(".../bb.php");
secondReq.CookieContainer = cookies
关于c# - 如何以编程方式检索 html 重定向网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/630575/