Testing user input is mirrored from one input to a

2019-08-02 02:33发布

问题:

I am trying to write a test in Selenium that ensures text entered into one input is mirrored in another input. I keep getting this error below.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]"}

This is the code I'm using currently:

class inputMirror(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://foo.bar")

def test_mirror_input(self):
#Ensures text from the first input is mirrored into the second input box
    driver = self.driver
    userInput = "Howdy"
    inputBoxOneXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]')
    inputBoxTwoXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[2]')
    inputBoxOneXpath.clear()
    inputBoxOneXpath.send_keys(userInput)
    driver.implicitly_wait(10)
    assert inputBoxTwoXpath.text == userInput
    driver.close()

HTML code:

<input type="text" placeholder="Enter text here..." value="">
<input class="textbox" placeholder="Enter text here..." value="" maxlength="80" required="true">

回答1:

The error says it all NoSuchElementException: Message: no such element which is because the xpath you constructed is unable to identify the intended element. Here is the code block for your reference :

driver = self.driver
userInput = "Howdy"
inputBoxOneXpath = driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']")
inputBoxOneXpath.clear()
inputBoxOneXpath.send_keys(userInput)
driver.implicitly_wait(10)
inputBoxTwoXpath = driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']")
assert inputBoxTwoXpath.get_attribute("value") in userInput
driver.close()


回答2:

With the provided html, you could do:

userInput = "Howdy"
driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']").send_keys(userInput)
driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']").send_keys(userInput)