Home > front end >  Selenium Firefox Webdriver - need help locating button and with code to click button
Selenium Firefox Webdriver - need help locating button and with code to click button

Time:01-17

I'm using Selenium and need to click on a button called Income Statement at enter image description here

CodePudding user response:

There are 2 problems here:

  1. You have to add wait / delay before accessing that element.
    This should preferably be done by expected conditions explicit waits.
  2. You are using a wrong locator.

This should work better:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'http://www.tradingview.com/screener'
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 20)
driver.get(url)
wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@data-set='income_statement']"))).click()

CodePudding user response:

Your xpath does not locate the right element in the HTMLDOM.

so instead of this:

//input[@name='Income Statement']

use this:

//div[@data-set='income_statement']

or

a CSS like this:

div[data-set = 'income_statement']

explanation:

See this is a outerHTML:

<div  data-set="income_statement">
                    Income Statement
                </div>

As we can see it is a div tag, so we are using //div and also it has data-set attribute income_statement and when you write the XPath, it is able to locate the right node with 1/1 uniqueness.

Also It's a best practise to use ExplicitWait:

wait = WebDriverWait(driver, 30)
try:
    wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@data-set='income_statement']"))).click()
    print('Clicked on the button')
except:
    print('Could not click ')
    pass

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  •  Tags:  
  • Related