[英]Scraping a website to get the element name and id through C# web browser
我正試圖抓一個網站來獲取Textarea
信息。
我正在使用:
HtmlDocument doc = this.webBrowser1.Document;
當我查看視圖源時,它顯示<textarea name="message" class="profile">
但當我嘗試訪問此textarea時:
HtmlDocument doc = this.webBrowser1.Document;
doc.GetElementsByTagName("textarea")
.GetElementsByName("message")[0]
.SetAttribute("value", "Hello");
它顯示錯誤:
Value of '0' is not valid for 'index'. 'index' should be between 0 and -1.
Parameter name: index
任何幫助?
根據您目前的需要,您可以簡單地使用:
doc.GetElementsByTagName("textarea")[0].InnerText = "Hello";
對於復雜的事物,您可以將HtmlDocument類與MSHTML類一起使用。
我可以委托給你HtmlAgilityPack !
我想你試圖訪問一個使用cookie的網站來確定用戶是否登錄(或不登錄)。 如果沒有,它將強制您注冊/登錄,否則您將無法看到任何內容。 我對嗎?
您的瀏覽器存儲該cookie,您的C#不存儲! (一般來說)
您需要創建一個cookie容器來解決該問題。
您的C#-App可以登錄,請求cookie /會話,可以從響應頭中獲取Cookie,然后您應該能夠抓取配置文件或任何您想要的內容。
獲取發布到服務器的發布數據。 你可以使用像Fiddler ,Tamper等工具/插件。
例如PostdataString: user_name = TESTUSER&password = TESTPASSWORD&language = en&action%3Asubmit = Submit
這是您可以使用的代碼段。
//Create the PostData
string strPostData = "user_name=" + txtUser.Text + "&password=" + txtPass.Text + "&language=en&action%3Asubmit=Submit";
CookieContainer tempCookies = new CookieContainer();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(strPostData);
//Create the Cookie
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.website.com/login.php");
request.Method = "POST";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.Accept = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "http://www.website.com/login.php";
request.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
string sRequestHeaderBuffer = Convert.ToString(response.Headers);
requestStream.Close();
//Stream(-output) of the new website
StreamReader postReqReader = new StreamReader(response.GetResponseStream());
//RichTextBox to see the new source.
richTextBox1.Text = postReqReader.ReadToEnd();
您需要在兩者之間調整Cookie參數,並添加當前的sessionid以及代碼。 這取決於您訪問的所請求的網站。
例如:
request.Headers.Add("Cookie", "language=en_US.UTF-8; StationID=" + sStationID + "; SessionID=" + sSessionID);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.