반응형
웹 페이지의 내용을 가져와 문자열 변수에 저장하는 방법
ASP.NET을 사용하여 웹 페이지의 내용을 가져올 수 있는 방법은 무엇입니까?웹 페이지의 HTML을 가져와서 문자열 변수에 저장하는 프로그램을 작성해야 합니다.
Web Client를 사용할 수 있습니다.
Using System.Net;
using(WebClient client = new WebClient()) {
string downloadString = client.DownloadString("http://www.gooogle.com");
}
웹 클라이언트에서 문제가 발생했습니다.이전에 문자열을 다운로드하십시오.사용할 경우 다음을 시도할 수 있습니다.
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을 사용/제거할 만큼 똑똑하지 않기 때문입니다.이로 인해 BOM이 발생할 수 있습니다(
) UTF-8 데이터가 반환될 때(최소한 문자 집합 없이) 문자열의 일부로 잘못 표시됨 - ic!
대신 다음과 같은 약간의 변화가 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을 전달합니다.htmlagility 팩을 사용하여 결과를 구문 분석할 수 있습니다.
저는 항상 WebClient를 사용해 왔지만, 이 게시물이 생성될 때(.NET 6이 사용 가능) WebClient는 더 이상 사용되지 않습니다.
선호되는 방법은
HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);
언급URL : https://stackoverflow.com/questions/4510212/how-i-can-get-web-pages-content-and-save-it-into-the-string-variable
반응형
'programing' 카테고리의 다른 글
대화형 편집 중에 내부 vim에서 Git rebase를 중단하는 방법 (0) | 2023.07.15 |
---|---|
크기의 내부 메커니즘(단위: C? (0) | 2023.07.15 |
SQL Server에서 작은 따옴표 바꾸기 (0) | 2023.07.15 |
Excel VBA에서 구현체를 사용하는 방법 (0) | 2023.07.15 |
유형 스크립트:튜플 유형에서 항목 제거 (0) | 2023.07.15 |