모든 HTML 태그 사이에 모든 단어를 가져 오는 것에 관한 스택 오버플로에 대한 몇 가지 게시물을 확인했습니다! 그들 모두는 나를 혼란스럽게 만들었다! 일부 사람들은 하나의 태그에 대해 정규 표현식을 특별히 권장하고 일부는 구문 분석 기법을 언급했습니다. 기본적으로 웹 크롤러를 만들려고합니다! 그게 내가 문자열에 내 프로그램에 가져온 링크의 HTML을 가지고있다! 나는 또한 내 데이터 문자열에 저장된 HTML에서 링크를 추출했습니다! 지금 나는 깊이를 통해 크롤 링하고 내 문자열에서 추출한 모든 링크의 페이지에서 단어를 추출하고 싶습니다! 나는 두 가지 질문이있어! 어떻게하면 태그와 자바 스크립트를 무시하고 각 웹 페이지에서 단어를 가져올 수 있습니까? 둘째 어떻게 재귀 적으로 링크를 통해 크롤링 할 것인가 ??
이것은 문자열에서 html을 얻는 방법입니다.
public void getting_html_code_of_link()
{
string urlAddress = "http://google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
data = readStream.ReadToEnd();
response.Close();
readStream.Close();
Console.WriteLine(data);
}
}
그리고 이것은 URL에서 링크 재 작성을 추출하는 방법입니다.
public void regex_ka_kaam()
{
StringBuilder sb = new StringBuilder();
//Regex hrefs = new Regex("<a href.*?>");
Regex http = new Regex("http://.*?>");
foreach (Match m in http.Matches(data))
{
sb.Append(m.ToString());
if (http.IsMatch(m.ToString()))
{
sb.Append(http.Match(m.ToString()));
sb.Append(" ");
//sb.Append("<br>");
}
else
{
sb.Append(m.ToString().Substring(1, m.ToString().Length - 1)); //+ "<br>");
}
}
Console.WriteLine(sb);
}
정규식 HTML 파일을 구문 분석을위한 좋은 선택이 아닙니다 ..
HTML은 엄격하지도 않고 포맷에도 규칙이 없습니다.
이것은 웹 페이지에서 모든 링크를 추출합니다.
public List<string> getAllLinks(string webAddress)
{
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlDocument newdoc=web.Load(webAddress);
return doc.DocumentNode.SelectNodes("//a[@href]")
.Where(y=>y.Attributes["href"].Value.StartsWith("http"))
.Select(x=>x.Attributes["href"].Value)
.ToList<string>();
}
이것은 html의 태그를 제외한 모든 내용을 가져옵니다.
public string getContent(string webAddress)
{
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlDocument doc=web.Load(webAddress);
return string.Join(" ",doc.DocumentNode.Descendants().Select(x=>x.InnerText));
}
이 링크를 통해 크롤링합니다.
public void crawl(string seedSite)
{
getContent(seedSite);//gets all the content
getAllLinks(seedSite);//get's all the links
}