2013-08-03 2 views
2

html을 사용하기 시작 했으므로 vba에서 합리적으로 사용할 수 있지만 두 가지를 연결하는 데는 몇 가지 문제가 있습니다.vba를 사용하여 웹에서 데이터 가져 오기

나는 웹 사이트에 등록을 통과하여 결과를 얻으려고합니다. 코드가 나는 결과를 얻을 다음 페이지를 새로 고칠 때까지 기다릴 필요가 지금까지

Dim HTMLDoc As HTMLDocument 
Dim MyBrowser As InternetExplorer 
    Sub GetVehicleDetails() 

    Dim MyHTML_Element As IHTMLElement 
    Dim MyURL As String 
    Dim x As Integer 
    On Error GoTo Err_Clear 
    MyURL = "http://www.1stchoice.co.uk/find-a-part" 
    x = 0 
    Set MyBrowser = New InternetExplorer 
    MyBrowser.Silent = True 
    MyBrowser.navigate MyURL 
    MyBrowser.Visible = True 
    Do 
    Loop Until MyBrowser.readyState = READYSTATE_COMPLETE 
    Set HTMLDoc = MyBrowser.document 
    HTMLDoc.all.license_plate.Value = "LV11VYT" 

    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("button") '("input") 
    'Get 2nd button 
    If MyHTML_Element.Title = "Continue" Then 'MyHTML_Element.Click: Exit For 
    x = x + 1 
    If x = 2 Then 
    MyHTML_Element.Click 
    End If 
    End If 
    Next 
Err_Clear: 
    If Err <> 0 Then 
    Err.Clear 
    Resume Next 
    End If 
    End Sub 

을 사용하지만, 밖으로

소스 코드가

<div id="block_subheader" class="block_editable block_wysiwyg"> 
<p>Almost there! <strong>TELL US</strong>&nbsp;which parts you need - <strong>ADD&nbsp;</strong>your contact details &amp; receive <strong>No Obligation Quotes</strong><span style="font-weight: normal;">&nbsp;to compare &amp; </span><span style="font-weight: normal;"><strong>Save &pound;&pound;'s!</strong></span></p>      
</div> 
<div class="clear"></div> 
<form id="step3" action="/find-a-part/step-3" method="post" enctype="multipart/form-data"> 
<div class="clearfix"> 
<h2>RENAULT MEGANE (X95) DYNAMIQUE TOMTOM DCI ECO 3 DOOR COUPE 1461cc (2011) DIESEL</h2> 
<p><a href="/find-a-part/step-2">Not quite the vehicle you're searching for? Click here to specify the vehicle exactly</a></p> 
</div> 
이다 나는 결과를 당겨하는 방법을 확실하지 않다

르노 메간 세부 정보를 얻으려고 시도

아무도 도와 줄 수 있습니까?

그래,이 부분을 지나쳤지만 버튼을 클릭 한 후 페이지가 변경되면 다른 문제가 발생했습니다. html.document를 새 페이지로 업데이트해야 할 때 코드를 사용할 때처럼 이전 소스 코드

나는 작동하도록 할 수 있지만 브라우저 이름이 무엇인지 말하기 위해 활성화 된 메시지 상자에서만 작동합니다.

제안 사항? 2003 또는 2007을 사용

Dim HTMLDoc As HTMLDocument 
Dim MyBrowser As InternetExplorer 

Sub GetVehicleDetails2() 

    Dim MyHTML_Element As IHTMLElement 
    Dim HTMLDoc As HTMLDocument, Doc As HTMLDocument 
    Dim MyURL As String, Vehicle As String 
    Dim x As Integer, y As Integer 
    On Error GoTo Err_Clear 
    MyURL = "http://www.1stchoice.co.uk/find-a-part" 
    x = 0 
    'open new explorer 
    Set MyBrowser = New InternetExplorer 
    MyBrowser.Silent = True 
    'navigate to page 
    MyBrowser.navigate MyURL 
    MyBrowser.Visible = True 
    'wait until ready 
    Do While MyBrowser.Busy Or _ 
    MyBrowser.readyState <> 4 
    DoEvents 
    Loop 
    Do 
    Loop Until MyBrowser.readyState = READYSTATE_COMPLETE 
    Set HTMLDoc = MyBrowser.document 

    'enter registration in text box 
    HTMLDoc.all.license_plate.Value = "LV11VYT" 

    'click continue button 
    Set MyHTML_Element = HTMLDoc.getElementsByTagName("button")(1) 
    MyHTML_Element.Click 
    Set HTMLDoc = Nothing 
    'wait until page updated 

    Set Doc = MyBrowser.document 
    'Application.Wait (Now() + "00:00:05") 

    'does not work if you take this out 
    MsgBox MyBrowser.FullName 

    'find text returned with vehicle details 
    For Each MyHTML_Element In Doc.getElementsByTagName("form") 
     If MyHTML_Element.ID = "step3" Then 
     Vehicle = MyHTML_Element.innerText 
     MsgBox Vehicle 
     End If 
    Next 
    'close browser down 
'MyBrowser.Quit 

Err_Clear: 
    If Err <> 0 Then 
    Err.Clear 
    Resume Next 
    End If 
    End Sub 

는 웹 쿼리를 시도하지 못할 패스 값 & 사용 버튼을 계속한다.

+0

Excel 버전을 표시하시기 바랍니다. 또한 : 당신은 wbe 쿼리를 실험 했습니까? 어떤 경우에는 거의 프로그래밍하지 않고 원하는 것을 할 수 있습니다! –

+0

필자는 Excel * web * 쿼리 –

+2

+1을 (상쾌하게 새로운 포스터와 비교하여) 첫 번째 합격점이 있음을 의미했습니다. –

답변

0

Regex (대 파서)를 사용하여 HTML에서 요소를 추출하는 것에 대한 인수를 시도하지 않고 Regex가 잘 정의되어 있고 그 요소 만 필요하기 때문에 필요한 요소를 추출하는 쉬운 방법이됩니다. .

당신이 뭔가를 할 수있는 (그리고 나는 당신의 예를 들어 작업 만하는 InStr을 사용하여 다른 방법을 제공하지만,이 경우 결과 많은 한 번에 반환 또는 구문 변경 등 다음 정규식 더 유연한 것) :

Sub blah() 

    Dim testStr As String 

    'test string you provided in the Question -> substitute it for your HTML return 
    testStr = ActiveSheet.Cells(1, 1).Value 

'Method 1: Use a simple Instr (fine for the example you provided, but if different bits you need to search are more complicated then you may need to use Regex instead 

    Dim startLocation As Long, endLocation As Long 
    Dim extractedText As String 

    startLocation = InStr(1, testStr, "<h2>", vbTextCompare) 

    If Not startLocation > 0 Then 

     Exit Sub 'or move to next or whatever 

    Else 

     endLocation = InStr(startLocation, testStr, "</h2>", vbTextCompare) 

     extractedText = Mid(testStr, startLocation + 4, endLocation - startLocation - 4) 

     Debug.Print "Basic InStr method: "; extractedText 

    End If 

'Method 2: Use Regex 

    'more flexible -> reference a Regex engine. 
    'This example uses Microsoft VBScript Regular Expressions 5.5 
    'That engine uses the same syntax as MS JavaScript regex 
    'See http://msdn.microsoft.com/en-us/library/1400241x.aspx for syntax 

    Dim regex As RegExp 
    Dim match As match 

    Set regex = New RegExp 

    With regex 

     .Pattern = "(?:<h2>)([\s\S]*?)(?=</h2>)" 
     'NB this regex engine does not support lookbehinds :-(
     'so we have to extract the submatched group for what we want 
     '(vs. just using Match.Value) 
     .IgnoreCase = True 
     .MultiLine = True 

     For Each match In .Execute(testStr) 

      Debug.Print "Regex match: "; match.SubMatches.Item(0) 

     Next match 

    End With 

End Sub 

출력은 다음과 같습니다

Basic InStr method: RENAULT MEGANE (X95) DYNAMIQUE TOMTOM DCI ECO 3 DOOR COUPE 1461cc (2011) DIESEL 
Regex match: RENAULT MEGANE (X95) DYNAMIQUE TOMTOM DCI ECO 3 DOOR COUPE 1461cc (2011) DIESEL 
+0

안녕하세요. 감사하지만 텍스트 문자열에서 가져올 필요가 없습니다. 나는 텍스트의 문자열을 보여주는 문서의 innertext를 얻는 방법을 찾으려고 노력했다. 나는 그것을 지금 분류했다. 그러나 어떻게해서든지 감사한다. –

관련 문제