Condividi:        

Prelevare dati da www.forebet.com usando i Driver Selenium

Vuoi potenziare i tuoi documenti Word? Non sai come si fa una macro in Excel? Devi creare una presentazione in PowerPoint?
Oppure sei passato a OpenOffice e non sei sicuro di come lavorare al meglio?

Moderatori: Anthony47, Flash30005

Prelevare dati da www.forebet.com usando i Driver Selenium

Postdi AndreaDeBiagi » 21/10/24 00:37

Ho provato a prelevare delle tabelle da una pagina web che ne ha 4 (una sola alla volta è attiva), ma solamente con Internet Explorer tutte le quattro tabelle vengono inserite correttamente sul foglio dati di excel, una sotto l'altra, mentre sia con Chrome, che con Edge, viene caricata correttamente solo la tabella selezionata.
Ho utilizzato questa procedura (guarda se va bene):
Codice: Seleziona tutto
Public Sub ScaricaDatiEdgeForum()
    Dim myURL As String
    Dim driver As New EdgeDriver
    Dim tabella As Object
    Dim th As Object
    Dim td As Object
    Dim r As Long
    Dim c As Integer
    Dim myStart As String
   
    myURL = InputBox("Inserire l'indirizzo della pagina web: ", "Indirizzo Sito Internet", "https://www.forebet.com/it/pronostici-svizzera/challenge-league/standing")
    If myURL = "" Then Exit Sub
    With driver
      .Start "Edge", ""
      .Get myURL
    End With
    myStart = Timer  'attesa addizionale
    Do
     DoEvents
     If Timer > myStart + 5 Or Timer < myStart Then Exit Do
    Loop
     
    Application.Goto (Sheets(Sheets.Count).Range("A1"))    '<<<< Foglio specifico
    Cells.Clear
    Set tabella = driver.FindElementByTag("TABLE")
    For Each th In tabella.FindElementsByTag("TR")
       r = r + 1: c = 1
       For Each td In th.FindElementsByTag("TD")
         If c >= 257 Then Exit For
         Cells(r, c).Value = td.Text
         c = c + 1
       Next
    Next
    Sheets(Sheets.Count).Cells.Select
    Selection.Style = "Normal"
    ActiveCell.Select
End Sub


In realtà, se non forzassi l'uscita dal ciclo for con questa istruzione:
If c >= 257 Then Exit For
la colonna c raggiungerebbe il valore massimo e la macro darebbe un errore di runtime in
Cells(r, c).Value = td.Text


Dagli un'occhiata
AndreaDeBiagi
Newbie
 
Post: 3
Iscritto il: 20/10/24 08:53

Sponsor
 

Re: Prelevare dati da www.forebet.com usando i Driver Seleni

Postdi Anthony47 » 21/10/24 12:30

Quel sito ha una struttura html alquanto strana; presenta 7 "Table" che sono annidate una nell'altra, quindi provare a leggere tutte le tabelle sarebbe un disastro.
Inoltre bisogna ricordare che Selenium mostra solo elementi visualizzati sulla pagina
Cio' detto, immaginando che le tabelle che ti interessano sono quelle corrispondenti ai 4 pulsanti Statistiche /Casa /Ospite /Seria (??), le ho estratte con la macro seguente:
Codice: Seleziona tutto
Public Sub ScaricaAsTabelle()
    Dim myURL As String
    Dim driver As New EdgeDriver
    Dim tabella As Object
    Dim r As Long
    Dim c As Integer
    Dim seqBtn, myMatch, RowText As String, tArr
   
    myURL = InputBox("Inserire l'indirizzo della pagina web: ", "Indirizzo Sito Internet", "https://www.forebet.com/it/pronostici-svizzera/challenge-league/standing")
    If myURL = "" Then Exit Sub
    With driver
'      .Start "Edge", ""
      .Start "Chrome", ""
      .Get myURL
    End With
    driver.Wait 5000
'
'La sequenza di selezione Tabelle
seqBtn = Array("standings-regular-season", "standings-home", "standings-away", "standings-last6")
'
    Application.Goto (Sheets(Sheets.Count).Range("A1"))    '<<<< Foglio specifico
    Cells.Clear
    Dim TC As Long, RC As Long, CC As Long
    Set tabella = driver.FindElementsByTag("TABLE")
    For TC = 1 To tabella.Count
        'considera solo le Tabelle "Standings":
        If InStr(1, tabella(TC).Attribute("class") & "   ", "standings", vbTextCompare) > 0 Then
            r = r + 1
            'Cerca quale tabella selezionare:
            myMatch = Application.Match(tabella(TC).Attribute("id"), seqBtn, 0)
            If Not IsError(myMatch) Then
                'seleziona una delle tabelle:
                driver.FindElementsByClass("std_head_btn")(myMatch).Click
                driver.Wait 1000
                Cells(r, 1).Value = "##Table " & TC & " di " & tabella.Count
                'Legge l'intera tabella:
                tArr = tabella(TC).AsTable.Data
                Cells(r + 1, 1).Resize(UBound(tArr), UBound(tArr, 2)).Value = tArr
                r = r + UBound(tArr) + 1
            End If
        End If
    Next TC
    Sheets(Sheets.Count).Cells.Select
    Selection.Style = "Normal"
    ActiveCell.Select
End Sub

Noterai che, identificata la collezione delle Tabelle (ne risultano 7), vado poi a gestire solo quelle cha hanno come Class "standings"; nell'ambito di queste controllo quale bottone va premuto per visualizzare la tabella adatta e solo allora procedo alla lettura /scrittura dei dati
Inoltre Selenium dispone del metodo "asTable" che consente di caricare direttamente su excel o in un array l'intero contenuto della tabella e questo consente di evitare il loop tra le TR e le TD

Spero che trovi qualche spunto per le tue ricerche
Avatar utente
Anthony47
Moderatore
 
Post: 19405
Iscritto il: 21/03/06 16:03
Località: Ivrea

Re: Prelevare dati da www.forebet.com usando i Driver Seleni

Postdi AndreaDeBiagi » 21/10/24 21:48

Si, così funziona, però, mi sembra di capire che il codice varia con la struttura del sito, mentre utilizzando Internet Explorer credo che la macro da utilizzare sia sempre la stessa, indipendentemente dalla pagina web dalla quale scaricare le relative tabelle.
Il codice vba che ho trovato, che utilizza Internet Explorer è il seguente:

Codice: Seleziona tutto
Public Sub ScaricaDatiWebIE()
Dim myURL As String
Dim IE As Object
Dim myStart As String
Dim myColl As Object
Dim myItm As Object
Dim trtr As Object
Dim tdtd As Object
Dim i As Integer
Dim j As Integer

myURL = InputBox("Inserire l'indirizzo della pagina web: ", "Indirizzo Sito Internet", "https://www.forebet.com/it/pronostici-svizzera/challenge-league/standing")
If myURL = "" Then Exit Sub
Set IE = CreateObject("InternetExplorer.Application")
   
With IE
   .navigate myURL
   .Visible = True
   Do While .Busy: DoEvents: Loop    'Attesa not busy
   Do While .readyState <> 4: DoEvents: Loop 'Attesa documento
End With

myStart = Timer  'attesa addizionale
Do
    DoEvents
    If Timer > myStart + 100 Or Timer < myStart Then Exit Do
Loop

'Leggi le tabelle, su un  foglio
Application.Goto (Sheets(Sheets.Count).Range("A1"))    '<<<< Foglio specifico
Cells.Clear
Set myColl = IE.document.getElementsByTagName("TABLE")
For Each myItm In myColl      '***1
    For Each trtr In myItm.Rows
        For Each tdtd In trtr.Cells
            Cells(i + 1, j + 1) = tdtd.innerText
            j = j + 1
        Next tdtd
        i = i + 1: j = 0
    Next trtr
i = i + 1
Next myItm                                             '***1
Sheets(Sheets.Count).Cells.Select
Selection.Style = "Normal"
ActiveCell.Select
'Chiusura IE
IE.Quit
Set IE = Nothing
End Sub

Se possibile, vorrei un codice universale, equivalente a questo che usa Internet Explorer, che valga per tutti i siti e che utilizzi un altro browser.
AndreaDeBiagi
Newbie
 
Post: 3
Iscritto il: 20/10/24 08:53

Re: Prelevare dati da www.forebet.com usando i Driver Seleni

Postdi Anthony47 » 21/10/24 22:47

Allora avevo capito male il motivo del tuo messaggio

vorrei un codice universale, equivalente a questo che usa Internet Explorer, che valga per tutti i siti e che utilizzi un altro browser

Purtroppo la tua rimane una pia illusione
Di base ogni pagina web necessita di un approccio diverso, anche se certe cose, ad esempio le tabelle (elementi <Table>), possono essere approcciate con delle tecniche comuni.
La biblioteca MSHTML.tlb, su cui si basano i comandi per IE, indirizza solo I.E., che nel frattempo e' stata abbandonato anche da Microsoft.
Per altri Browser esistono altri ambienti; Selenium e' uno di questi
Molte cose su Selenium sono eseguite peggio che con mshtml.tlb, ma meno male Selenium c'è, visto che molti siti non sono piu' compatibili con IE perche' non supporta standard minimi di sicurezza.
Avatar utente
Anthony47
Moderatore
 
Post: 19405
Iscritto il: 21/03/06 16:03
Località: Ivrea


Torna a Applicazioni Office Windows


Topic correlati a "Prelevare dati da www.forebet.com usando i Driver Selenium":


Chi c’è in linea

Visitano il forum: Nessuno e 11 ospiti