반응형
웹 페이지의 콘텐츠를 가져 와서 문자열 변수에 저장하는 방법
ASP.NET을 사용하여 웹 페이지의 콘텐츠를 얻으려면 어떻게해야합니까? 웹 페이지의 HTML을 가져 와서 문자열 변수에 저장하는 프로그램을 작성해야합니다.
WebClient를 사용할 수 있습니다.
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
이전에 Webclient.Downloadstring에 문제가 발생했습니다. 그렇다면 다음을 시도 할 수 있습니다.
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
사용 하지 않는 것이 좋습니다 WebClient.DownloadString
. 이는 (적어도 .NET 3.5에서는) DownloadString이 BOM을 사용 / 제거 할만큼 똑똑하지 않기 때문입니다. 이로 인해 
UTF-8 데이터가 반환 될 때 (적어도 문자 집합없이) BOM ( )이 문자열의 일부로 잘못 표시 될 수 있습니다 .
대신이 약간의 변형이 BOM에서 올바르게 작동합니다.
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
Webclient client = new Webclient();
string content = client.DownloadString(url);
원하는 페이지의 URL을 전달하십시오. htmlagilitypack을 사용하여 결과를 구문 분석 할 수 있습니다.
반응형
'programing tip' 카테고리의 다른 글
Eclipse가 시작되지 않고 로그 오류 메시지 : ObjectNotFoundException : 트리 요소 (0) | 2020.10.31 |
---|---|
여러 값과 일치하는 if 문 (0) | 2020.10.31 |
알림을 표시하지 않고 Foreground ()를 시작하는 방법은 무엇입니까? (0) | 2020.10.31 |
프로젝트의 / resources 폴더에있는 파일의 절대 경로를 얻는 방법 (0) | 2020.10.31 |
C-숫자가 소수인지 확인 (0) | 2020.10.31 |