2009-11-07 4 views
0

WebBrowser 컨트롤에서 특정 웹 페이지를로드하고 있습니다. 이 페이지 내에있는 다음 HTML을 가져 와서 문자열로 저장 한 다음 트리밍 할 수 있습니까?WebBrowser 내에서 HTML 코드 조각 잘라 내기

HTML 코드 조각 : 트림

<div class="alertText">26 friends joined</div> 

:

26

내가 매우 모호한 설명 미안 해요,하지만 난 정말 모르겠어요 여기

은 예입니다 이 말을하는 법. 고맙습니다.

답변

1

HtmlElement 유형을 열거하지 않고 방금 정규식을 사용하여 HTML을 검색하는 것이 어떨까요? 당신이 outerbits을 드롭 할 수있는 HTML에 덜 의존하는 스크래핑을 원한다면

html = WebBrowser1.Document.documentElement.OuterHTML 
pattern = @'<div class="alertText">(\d{1,2}) friends joined</div>' 
for Match m in Regex.Matches(html, pattern) { 
    friendsJoined = Convert.ToInt32(m.Groups[1].Value) 
} 

...

html = WebBrowser1.Document.documentElement.OuterHTML 
pattern = @'>(\d{1,2}) friends joined</' 
for Match m in Regex.Matches(html, pattern) { 
    friendsJoined = Convert.ToInt32(m.Groups[1].Value) 
} 
+0

작동하지 않는 것 같습니다. – user

+0

그 이상의 세부 사항이 필요합니다. –

+0

'WebBrowser'에는'documentElement' 속성이 없습니다.'webBrowser1.Document.Body.OuterHTML'을 사용하거나'webBrowser1.Document.DomDocument'와 함께 관리되지 않는 mshtml 인터페이스를 사용해야합니다. – Majkel

0

당신은 같은 것을 의미합니까 :

string numberOfFriends; 

HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("div"); 
foreach(HtmlElement elem in elems) 
{ 
    string className = elem.GetAttribute("className"); 
    if(!string.IsNullOrEmpty(className) && "alertText".Equals(className)) 
    { 
    string content = elem.InnerText; 
    if(Regex.IsMatch(content, "\\d+ friends joined")) 
    { 
     numberOfFriends = Regex.Match(content, "(\\d+) friends joined").Groups[ 1 ].Value; 
    } 
    } 
} 

내가 정규식 완전히 올바른지 완전히 확실하지 않다,하지만 나머지는 작동합니다.

편집 : 변경됨 Groups[ 0 ] ~ Groups[ 1 ] - IIRC 첫 번째 그룹은 전체 일치입니다.

편집 2 : elem.GetAttribute("className")elem.GetAttribute("class")을 변경 - 속성의 이름과 고정 변수 이름 (className-class)를 고정.

+0

작동하지 않는 것 같습니다. – user

+0

어느 부분입니까? 클래스는 예약어로, 내 컴퓨터에있을 때 나머지를 확인합니다. – Majkel

+0

OK, 이제 작동합니다 - 속성 이름이 잘못되었습니다. – Majkel

0

나는 이것이 더 나은 정규식 일치라고 말할 것입니다;

html = WebBrowser1.Document.documentElement.OuterHTML 
pattern = @'(\d+)\sfriends\sjoined' 
for Match m in Regex.Matches(html, pattern) { 
    friendsJoined = Convert.ToInt32(m.Groups[1].Value) 
} 
관련 문제