我是这个网络爬行世界的新手。那么任何人都在网络应用程序上进行网络爬行?如果有人使用asp.net& C#不是 VB.NET窗体。
我有一个带有3个文本框和一个按钮的默认网页表单,这是后面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
String Rstring;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
WebRequest myWebRequest;
WebResponse myWebResponse;
String URL = TextBox1.Text;
myWebRequest = WebRequest.Create(URL);
myWebResponse = myWebRequest.GetResponse();//Returns a response from an Internet resource
Stream streamResponse = myWebResponse.GetResponseStream();//return the data stream from the internet
//and save it in the stream
StreamReader sreader = new StreamReader(streamResponse);//reads the data stream
Rstring = sreader.ReadToEnd();//reads it to the end
String Links = GetContent(Rstring);//gets the links only
TextBox2.Text = Rstring;
TextBox3.Text = Links;
streamResponse.Close();
sreader.Close();
myWebResponse.Close();
}
//public ISet<string> GetNewLinks(string content)
//{
// Regex regexLink = new Regex("(?<=<a\\s*?href=(?:'|\"))[^'\"]*?(?=(?:'|\"))");
// ISet<string> newLinks = new HashSet<string>();
// foreach (var match in regexLink.Matches(content))
// {
// if (!newLinks.Contains(match.ToString()))
// newLinks.Add(match.ToString());
// }
// return newLinks;
//}
private String GetContent(String Rstring)
{
String sString = "";
HTMLDocument d = new HTMLDocument();
IHTMLDocument2 doc = (IHTMLDocument2)d;
doc.write(Rstring);
IHTMLElementCollection L = doc.links;
foreach (IHTMLElement links in L)
{
sString += links.getAttribute("href", 0);
sString += "/n";
}
return sString;
}
}
答案 0 :(得分:1)
我知道这是一个老问题,但它从来没有得到回答所以这里什么也没有,也许这会对某人有所帮助。
我设法让您的代码工作,并通过改变您获取内容的方式获得所有链接:
private string GetContent(String Rstring)
{
String sString = "";
String temp = "";
mDocument.LoadHtml(Rstring);
IEnumerable<HtmlNode> links = mDocument.DocumentNode.Descendants("a");
foreach (HtmlNode link in links)
{
temp = link.GetAttributeValue("href", "");
if (temp.StartsWith("https://") || temp.StartsWith("http://"))
sString += temp + "\n";
else
continue;
}
return sString;
}
所以我去获取页面中的所有元素然后如果它们有一个有效的链接我将它添加到字符串并返回它。