How do I click a button if a specific target is there?

Asked

Viewed 33 times

0

Depending on the CNPJ I carry, it generates a new anchor, with a different ID, then I need to click this

<a id="menuPrincipal_divLinks3" title="" href="../Relatorio/GerarRelatorio.asp" target="palco">Gerar Relatório</a>

How do I make it click only if the target is >generate report< ?

Click by the ID not of the pq it changes ID depending on the CNPJ, and by the Xpath also not of, it changes position

1 answer

0

What you can do to solve this is:

  1. Get all links from page:

    links = driver.find_elements_by_xpath("//a[@href]")

(Assuming the variable used to handle the page is called driver)

  1. Scroll through the obtained links, and, getting the attribute target, click on the link if the value of this attribute equals "generate report":

    #Supondo que a importação do webdriver foi feita com o nome de 'webdriver'
    wait = WebDriverWait(webdriver, 10)
    
    for link in links:
      valor_target = link.get_attribute('target')
    
      if(valor_target == 'Gerar Relatório'): 
          try: #Para evitar TimeoutException
              espera = wait.until(EC.visibility_of(link)) 
              #A espera seria para evitar que ocorra ElementNotInteractableException
              link.click()
              #A linha abaixo também serve para evitar ElementNotInteractableException,
              #alternando a aba para a primeira que está aberta
              #(supondo que sua página ficará aberta na primeira aba)
              driver.switch_to.window(driver.window_handles[0])
          except TimeoutException as ex:
              print('Timeout excedido: ' + ex.msg)
    

To run the above code, you need to make the following imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
  • Thank you very much brother

Browser other questions tagged

You are not signed in. Login or sign up in order to post.