在c# Windows窗体应用程序中获取当前页面的Html源代码
本文关键字:当前页 Html 源代码 获取 Windows 窗体 应用程序 | 更新日期: 2023-09-27 18:11:45
我正在使用BandOjects和c# Windows Forms Application创建一个Internet Explorer插件,并正在测试解析HTML源代码。我目前一直在根据网站的URL解析信息。
我想获得一个示例网站的当前页面的HTML来源,我有使用登录。如果我使用我所在页面的URL,它将总是抓取登录页面的源而不是实际页面,因为我的应用程序无法识别我登录了。我是否需要使用某种api存储站点的登录凭据?或者是否有一种方法可以抓取HTML的当前页面?我更喜欢后者,因为它似乎会少些麻烦。谢谢!
我在我的一个应用中使用了这个方法:
private static string RetrieveData(string url)
{
// used to build entire input
var sb = new StringBuilder();
// used on each read operation
var buf = new byte[8192];
try
{
// prepare the web page we will be asking for
var request = (HttpWebRequest)
WebRequest.Create(url);
/* Using the proxy class to access the site
* Uri proxyURI = new Uri("http://proxy.com:80");
request.Proxy = new WebProxy(proxyURI);
request.Proxy.Credentials = new NetworkCredential("proxyuser", "proxypassword");*/
// execute the request
var response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
} while (count > 0); // any more data to read?
}
catch(Exception exception)
{
MessageBox.Show(@"Failed to retrieve data from the network. Please check you internet connection: " +
exception);
}
return sb.ToString();
}
你只需要传递你需要检索代码的网页的url。
例如:string htmlSourceGoggle = RetrieveData("www.google.com")
注意:如果您使用代理访问互联网,可以取消代理配置的注释。将代理地址、用户名和密码替换为您使用的代理地址、用户名和密码。
用于通过代码登录。登录到网站,通过c#