【问题标题】:How do I prevent Selenium Chrome webdriver from passing send_keys multiple times?如何防止 Selenium Chrome webdriver 多次传递 send_keys?
【发布时间】:2020-07-12 17:17:14
【问题描述】:

我正在学习网络自动化,作为一个测试用例,我尝试在 expedia 上搜索航班并将日期值传递到给定的出发/返回文本框中。对于第一个文本框,一切都很好,send_keys 可以按预期工作,但是由于第二个(或返回日期文本框)的某些原因,send_keys 似乎同时传递了前一个日期和我希望它传递的日期第二个时间。如果你运行我的代码,很清楚会发生什么,但这里也有一张图片:

我不知道这是否仅仅是因为 expedia 设置文本框的方式,还是因为我没有经验而在编程中搞砸了,但我们将不胜感激。

到目前为止,这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome(executable_path='E:\Webdrivers\chromedriver.exe')

driver.implicitly_wait(5)
driver.get('https://www.expedia.com/')
driver.maximize_window()

driver.find_element_by_id('tab-flight-tab-hp').click() #clicks flight button
#driver.find_element(By.ID, 'tab-flight-tab-hp').click() can also be used to click flight button

time.sleep(2)
driver.find_element_by_id('flight-origin-hp-flight').send_keys('NYC') #Origin
driver.find_element_by_id('flight-destination-hp-flight').send_keys('Toronto') #Destination


driver.find_element_by_id('flight-departing-hp-flight').clear()
driver.find_element_by_id('flight-departing-hp-flight').send_keys('12/28/2020') #Departing

time.sleep(1)

driver.find_element_by_id('flight-returning-hp-flight').clear()
driver.find_element_by_id('flight-returning-hp-flight').send_keys("01/15/2021")

time.sleep(5)

driver.find_element_by_xpath('//*[@id="gcw-flights-form-hp-flight"]/div[8]/label/button').click()

【问题讨论】:

    标签: python selenium selenium-chromedriver webautomation


    【解决方案1】:

    该站点被配置为返回日期与出发日期相同。即使您在发送密钥之前使用 clear(),当您使用 send_keys() 时,命令首先会点击那里。它会导致输入出发日期。接下来是你在 send_keys() 中传递的内容 所以你可以做的是发送退格键清除日期,然后输入新的返回日期。

      back = Keys.BACK_SPACE * 10 #mm/dd/yyyy counts to 10 characters
      driver.find_element_by_id('flight-returning-hp-flight').send_keys(back + "01/15/2021")
    

    这样,当命令遇到 send_keys() 时,站点会自动输入出发日期,然后您发送退格键,然后键入返回日期。我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      相关资源
      最近更新 更多