selenium 可以自动检测网页上的文本框并输入值吗?

Can selenium automatically detect text box on webpage and input values?

我是测试自动化的新手。通过学习一些基本的 selenium,我知道我可以使用 selenium 工具在线填写一些表格。以下是我正在使用的一些代码供您参考:

elem = self.driver.find_element_by_xpath("//*[@title='Registration']")
elem.click()
iframe = self.driver.find_elements_by_id('frm_reg_load_patient')[0]
self.driver.switch_to.default_content()
self.driver.switch_to.frame(iframe)
elem = self.driver.find_element_by_id("txtPatientLastName")
elem.clear()
elem.send_keys("Peng")
elem = self.driver.find_element_by_id("txtPatientFirstName")
elem.clear()
elem.send_keys("Richard")

这是网络截图:

我的问题,是否可以自动找到文本框并填写一些随机值。我只是测试是否可以创建新记录,所以值并不重要。

谢谢

由于所需的元素在 <iframe> 中,因此您必须:

  • 诱导 WebDriverWait 以获得所需的 框架并切换到它
  • 诱导 WebDriverWait 使所需的 元素可点击
  • 您可以使用以下解决方案:

    WebDriverWait(self.driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"frm_reg_load_patient")))
    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, "txtPatientLastName"))).send_keys("Peng")
    self.driver.find_element_by_id("txtPatientFirstName").send_keys("Richard")
    
  • 注意:您必须添加以下导入:

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

更新

根据您的评论更新,您的 script/program 将 隐式等待 替换为 WebDriverWait 会更有效,但老实说没有现成的 function() 可用于扫描页面以查找任何元素填写随机数据。编写一个新的 wrapper 函数将以更好的方式满足您的需求,但这应该 超出此问题的范围

我自己找到了答案。如果有人有同样的问题:

//find all input fields where type = text or password and store them In array list 
txtfields.
 List<WebElement> txtfields = driver.findElements(By.xpath("//input[@type='text' or 
 @type='password']"));

//for loop to send text In all text box one by one.
 for(int a=0; a<txtfields.size();a++){   
 txtfields.get(a).sendKeys("Text"+(a+1));  
 }
 Thread.sleep(3000);