Search code examples
rweb-scrapingrselenium

How to get new generated url after using clickElement function from RSelenium package


I would like to know how to get a url after using the clickElement function from R's RSelenium package. Here's an example:

library(RSelenium)
rD <- rsDriver(browser = c("chrome"), 
               chromever = "98.0.4758.102", 
               #extraCapabilities = list(chromeOptions = list(args = list("--headless"))),
               port = 4580L)

driver <- rD[["client"]]

urll <- "https://www.zapimoveis.com.br/venda/fazendas-sitios-chacaras/ms+campo-grande/?pagina=1"

driver$navigate(urll)
 
linkimovdescr <- driver$findElement(using = "xpath",
                                    "/html/body/main/section[1]/div[2]/div[3]/section/div/div[1]")
                 
linkimovdescr$clickElement()

Here's the question! How to get the address "https://www.zapimoveis.com.br/imovel/venda-fazenda-sitio-chacara-parque-do-sol-campo-grande-ms-240m2-id-2531139106/"

Note: The linkimovdescr$getCurrentUrl() or driver$getCurrentUrl() command does not answer my question, as it keeps pointing to the home page.

Thanks for any help.


Solution

  • As new tab opens when you click the item, thus we need to switch tabs in order to get url.

    1.Clicking the item

    linkimovdescr <- driver$findElement(using = "xpath",
                                        "/html/body/main/section[1]/div[2]/div[3]/section/div/div[1]")
                     
    linkimovdescr$clickElement()
    

    2.Now get the list of all the tabs by getWindowHandles

    df =  driver$getWindowHandles()
    

    3.Now switch to the second tab

    driver$switchToWindow(df[[2]])
    

    4.Get the url,

    driver$getCurrentUrl() 
    [[1]]
    [1] "https://www.zapimoveis.com.br/imovel/venda-fazenda-sitio-chacara-zona-rural-campo-grande-ms-30000m2-id-2552129433/"