Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get href link using python playwright

I am trying to extract the link inside a href but all I am finding it is the text inside the element

The website code is the following:

<div class="item-info-container ">
   <a href="/imovel/32600863/" role="heading" aria-level="2" class="item-link xh-highlight" 
   title="Apartamento T3 na avenida da Liberdade, São José de São Lázaro e São João do Souto, Braga">
   Apartamento T3 na avenida da Liberdade, São José de São Lázaro e São João do Souto, Braga
   </a>

And the code I am using is:

element_handle = page.locator('//div[@class="item-info-container "]//a').all_inner_texts()

No matter if I specify //a[@href] or not, my output is always the title text:

Apartamento T3 na avenida da Liberdade, São José de São Lázaro e São João do Souto, Braga

When what I really want to achieve is:

/imovel/32600863/

Any ideas of where my logic is failing me?

like image 557
gustavo matteo Avatar asked May 11 '26 08:05

gustavo matteo


2 Answers

Using get_attribute:

link = page.locator('.item-info-container ').get_by_role('link').get_attribute('href')

More than one locator:

link_locators = page.locator('.item-info-container ').get_by_role('link').all()
for _ in link_locators:
    print(_.get_attribute('href'))
like image 99
candre Avatar answered May 12 '26 20:05

candre


Managed to do it by finding all elements and then getting the attribute after handling all elements.

handleLinks = page.locator('//div[@class="item-info-container "]/a')
    for links in handleLinks.element_handles():
        linkF = links.get_attribute('href')
        print(linkF)

and the outcome would be:

/imovel/32611494/
/imovel/32642523/
/imovel/32633771/
/imovel/32527162/
/imovel/30344934/
/imovel/31221488/
/imovel/32477875/
/imovel/31221480/
/imovel/32450120/
/imovel/32515628/
/imovel/32299064/
like image 27
gustavo matteo Avatar answered May 12 '26 22:05

gustavo matteo