【问题标题】:Testing user input is mirrored from one input to another with Selenium + Python使用 Selenium + Python 将测试用户输入从一个输入镜像到另一个输入
【发布时间】:2018-04-29 01:39:00
【问题描述】:

我正在尝试在 Selenium 中编写一个测试,以确保输入到一个输入中的文本镜像到另一个输入中。我在下面不断收到此错误。

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]"}

这是我目前正在使用的代码:

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 代码:

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

【问题讨论】:

  • 能否提供正确的 HTML 代码?
  • 将 html 添加到问题中,如果不清楚,请告诉我。
  • 在您的代码中,您使用的是绝对 xpath。使用提供的 html 没有人可以帮助您解决您的错误。

标签: python selenium automation automated-tests


【解决方案1】:

错误说明了一切NoSuchElementException: Message: no such element,这是因为您构造的xpath 无法识别预期的元素。这是供您参考的代码块:

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()

【讨论】:

  • 这解决了我的问题,谢谢! assert inputBoxTwoXpath.get_attribute("value") in userInput
【解决方案2】:

使用提供的 html,您可以:

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)

【讨论】:

  • @CalCorbin 很高兴为您提供帮助。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受:stackoverflow.com/help/someone-answers
猜你喜欢
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 2016-10-30
  • 1970-01-01
  • 2019-10-13
相关资源
最近更新 更多