Asp.Net c#登录到另一个网站
本文关键字:另一个 网站 登录 Net Asp | 更新日期: 2023-09-27 18:17:08
我知道这个问题已经被问过很多次了,这就是我是如何得到我在下面的代码,但我只是不能让它在我试图访问的特定网站上工作的。在我试图访问的网站上,我需要从页面检索某些值,但是像价格和可用性这样的东西只有在登录后才会出现,所以我试图提交我的登录信息,然后转到产品页面,使用HTML Agility Pack获取我需要的信息。
目前它似乎试图登录,但网站要么不接受它,要么在下一页加载时不存在cookie,以实际保持我登录。
如果有人可以帮助我这个我将非常感激,因为我不是一个程序员,但已经分配了这个任务作为软件安装的一部分。
protected void Button5_Click(object sender, System.EventArgs e)
{
string LOGIN_URL = "http://www.videor.com/quicklogin/1/0/0/0/index.html";
string SECRET_PAGE_URL = "http://www.videor.com/item/47/32/0/703/index.html?scriptMode=&CUSTOMERNO=xxx&USERNAME=xxx&activeTabId=0";
// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
// first, request the login form to get the viewstate value
HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream()
);
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string postData = "CUSTOMERNO=xxxx&USERNAME=xxxxx&PASSWORD=xxxxx";
// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
// we don't need the contents of the response, just the cookie it issues
webRequest.GetResponse().Close();
// now we can send out cookie along with a request for the protected page
webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
// and read the response
responseData = responseReader.ReadToEnd();
responseReader.Close();
Response.Write(responseData);
}
这不是一个直接的答案,因为我不确定你的代码出了什么问题(从粗略的看它看起来不错),但另一种方法是使用Selenium使用浏览器自动化。下面的代码将使用Chrome浏览器加载页面(您可以替换Firefox或IE),并且更容易编写代码。如果他们添加javascript或其他东西,它也不会中断。
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(LOGON_URL);
driver.FindElement(By.Id("UserName")).SendKeys("myuser");
driver.FindElement(By.Id("Password")).SendKeys("mypassword");
driver.FindElement(By.TagName("Form")).Submit();
driver.Navigate().GoToUrl(SECRET_PAGE_URL);
// And now the html can be found as driver.PageSource. You can also look for
// different elements and get their inner text and stuff as well.