Home > Back-end >  Selenium (python): how do I fetch only the first element with href
Selenium (python): how do I fetch only the first element with href

Time:01-02

With the following code I am fetching links I need from within some items but for unknown reasons within it there are TWO identical <a tags with the identical contents.

<span >
<a href="/atto/serie_generale/caricaDettaglioAtto/originario?atto.dataPubblicazioneGazzetta=2021-12-31&amp;atto.codiceRedazionale=21A07813&amp;elenco30giorni=false">
<span >
ORDINANZA 31 dicembre 2021
</span>
</a>
<a href="/atto/serie_generale/caricaDettaglioAtto/originario?atto.dataPubblicazioneGazzetta=2021-12-31&amp;atto.codiceRedazionale=21A07813&amp;elenco30giorni=false">
Ulteriori misure  urgenti  in  materia  di  contenimento  e  gestione
dell'emergenza  epidemiologica  da  COVID-19  nelle  Regioni   Lazio,
Liguria,  Lombardia,  Marche,  Piemonte,  Sicilia,  Veneto  e   nelle
Province autonome di Trento e Bolzano. (21A07813) 
<span >
</span>
<span >Pag. 17</span>
</a>
</span>

How can I fetch only one of them?

atti = [
        my_elem.get_attribute("href")
        for my_elem in WebDriverWait(driver, 5).until(
            EC.visibility_of_all_elements_located(
                (By.CSS_SELECTOR, "span.risultato > a")
            )
        )
    ]

CodePudding user response:

To fetch the first href you can use either of the following Locator Strategies:

  • CSS_SELECTOR as first-child:

    for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.risultato > a:first-child"))):
    
  • CSS_SELECTOR as first-of-type:

    for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.risultato > a:first-of-type"))):
    
  • Related