Home > Back-end >  How to send keys to an element with type = number using Selenium Python?
How to send keys to an element with type = number using Selenium Python?

Time:05-05

I am trying to send a number to an element (a textbox) that only takes number values. This element is as follows:

Currently, I have this code (the code under this paragraph) to input a number into the element. Could anyone tell me why the number isn't showing up? Any help would be appreciated.

bpm = 121
inputBpm = driver.find_element(By.XPATH, "/html/body/mp-root/div/ ... /div[3]/div/input")
inputBpm.clear()
inputBpm.send_keys(str(bpm))

Edit: Here's a visual of what I'm trying to type into (after it's been cleared) The textbox

Here's the surrounding element:

<div _ngcontent-soo-c572="" >
<label _ngcontent-soo-c572="" >BPM</label>
<span _ngcontent-soo-c572="" >(Beats per minute)</span>
<div _ngcontent-soo-c572="" >
<input _ngcontent-soo-c572="" type="number" name="bpm" placeholder="0" min="0" max="999" step="0.01" ></div>
</div>

CodePudding user response:

You can simply do,

if inputBpm.get_attribute("type")  == "number":
    inputBpm.clear()
    inputBpm.send_keys(str(bpm))

Or you can just find that input tag with type = number using XPATH.

input_tag = driver.find_element(By.XPATH, "//input[contains(@type, 'number')]")
inputBpm.clear()
input_tag.send_keys("9023")

CodePudding user response:

The <input> element is have the attributes type="number", min="0" and max="999"

<input _ngcontent-pxo-c572="" type="number" name="bpm" placeholder="0" min="0" max="999" step="0.01" >

Solution

To send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    bpm = 121
    my_element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ng-valid.ng-touched.ng-dirty[name='bpm']")))
    my_element.click()
    my_element.clear()
    my_element.send_keys(str(bpm))
    
  • Using XPATH:

    bpm = 121
    my_element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-valid ng-touched ng-dirty' and @name='bpm']")))
    my_element.click()
    my_element.clear()
    my_element.send_keys(str(bpm))
    
  • Note: You have to add the following imports :

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