Python Selenium send_keys等待

6

我有一个关于send_keys函数的问题。如何让测试等待send_keys输入的全部内容?我不能使用time.sleep,所以我尝试了以下方法:

WebDriverWait(self.browser, 5).until(
            expected_conditions.presence_of_element_located((By.ID, "name")))
query = driver.find_element_by_id('name') 
query.send_keys('python')
driver.find_element_by_id("button").click()

应用在操作未完成时就点击了按钮 send_keys,谢谢回答。


一种方法是轮询元素的文本值。只要没有从webelement返回单词python,就不要立即点击。(尽管在您的示例中,我相当确定在点击之前使用time.sleep(1)可以解决问题,但您不想使用它) - Chuk Ultima
你有什么证据表明在输入所有按键之前点击已经发生了吗?send_keys完成之前返回的可能性似乎不大。例如,您是否尝试在单击之前获取元素的值,以查看浏览器返回的内容?是不是您的输入元素附加了一些JavaScript代码,导致了某种延迟? - Bryan Oakley
1
谢谢,我有一个问题,因为这是针对一个元素的。如果我有一个列表怎么办?我必须等待所有元素。然后使用send_keys并从列表中选择一个项目吗? - Tom1416
@Tom1416,你需要哪些元素?你的脚本具体要做什么? - Andersson
1
我想等待所有列表项,并使用 send_keys 选择一个项目,例如:query.send_keys('python')。 - Tom1416
3个回答

6
您可以尝试使用以下代码:

query = WebDriverWait(self.browser, 5).until(
            expected_conditions.presence_of_element_located((By.ID, "name")))
query.send_keys('python')
WebDriverWait(self.browser, 5).until(lambda browser: query.get_attribute('value') == 'python')
self.browser.find_element_by_id("button").click()

这段代码应该能让你等待直到在字段中输入完整的字符串。

1
#to use send_keys
from selenium.webdriver.common.keys import Keys     

#enter a url inside quotes or any other value to send
url = ''
#initialize the input field as variable 'textField'                     
textField = driver.find_element_by........("")
#time to wait       
n = 10
#equivalent of do while loop in python                          
while (True):   #infinite loop                  
    print("in while loop")
    #clear the input field
    textField.clear()                   
    textField.send_keys(url)
    #enter the value
    driver.implicitly_wait(n)
    #get the text from input field after send_keys
    typed = textField.get_attribute("value")    
    #check whether the send_keys value and text in input field are same, if same quit the loop  
    if(typed == url):                   
      print(n)
      break
    #if not same, continue the loop with increased waiting time
    n = n+5 

0
如果我正确理解了你的问题,你有一个Web控件,提供一个“搜索”字段,它将根据字段内容逐步过滤列表。因此,当你输入“python”时,你的列表将被缩减为与“python”匹配的项目。在这种情况下,你需要使用你的代码,但是添加一个额外的等待,直到列表中匹配的项目出现。类似于这样:
WebDriverWait(self.browser, 5).until(
            expected_conditions.presence_of_element_located((By.ID, "name")))
query = driver.find_element_by_id('name') 
query.send_keys('python')
options_list = some_code_to_find_your_options_list
target_option = WebDriverWait(options_list, 5).until(expected_conditions.presense_of_element_located((By.XPATH, "[text()[contains(.,'python')]]")))
driver.find_element_by_id("button").click()

这一切都假设按钮选择了所选项目。


1
谢谢,我有一个问题,因为我可以通过XPATH访问我的列表,但我不知道如何选择元素,因为应用程序不会点击元素。 - Tom1416

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接