Javascript 如何在签入和签出字段中发送不同的日期https://www.expedia.co.in/ 通过Python使用Selenium

Javascript 如何在签入和签出字段中发送不同的日期https://www.expedia.co.in/ 通过Python使用Selenium,javascript,python,selenium,selenium-chromedriver,webdriverwait,Javascript,Python,Selenium,Selenium Chromedriver,Webdriverwait,我正在写一个简单的代码来选择Expedia中的到达地点、离开地点、到达日期和离开日期 除了到达日期和离开日期显示相同外,一切都很好 从selenium导入webdriver 从selenium.webdriver.common.by导入 导入时间 driver=webdriver.Firefox(可执行文件_path=“C:/bin/geckodriver.exe”) 驱动程序。隐式等待(20) 驱动程序。最大化_窗口() 驱动程序。获取(“https://www.expedia.co.in/"

我正在写一个简单的代码来选择Expedia中的到达地点、离开地点、到达日期和离开日期

除了到达日期和离开日期显示相同外,一切都很好

从selenium导入webdriver
从selenium.webdriver.common.by导入
导入时间
driver=webdriver.Firefox(可执行文件_path=“C:/bin/geckodriver.exe”)
驱动程序。隐式等待(20)
驱动程序。最大化_窗口()
驱动程序。获取(“https://www.expedia.co.in/")
driver.find_元素(By.ID,“tab flight tab hp”)。单击()
驱动程序。查找元素(通过.ID,“航班始发地hp航班”)。发送密钥(“SFO”)
时间。睡眠(2)
驱动程序。查找元素(通过.ID,“航班目的地hp航班”)。发送密钥(“NYC”)
驾驶员。查找要素(由ID“hp航班起飞”)。发送密钥(“2019年6月7日”)
时间。睡眠(2)
driver.find_元素(By.ID,“航班返回hp航班”).clear()
driver.find_元素(By.XPATH,“//input[@id='flight-returning-hp-flight'])。发送_键(“2019年6月10日”)
driver.find_元素(By.XPATH,“//form[@id='gcw-flights-form-hp-flights']//按钮[@class='btn-primary btn action gcw submit']”。单击()
输出屏幕截图:


根据您的用例,当您在与文本签入关联的元素中设置值时,似乎会在与文本签出关联的元素中自动填充相同的值。要在与文本相关联的元素中设置不同的日期,请使用以下解决方案:

  • 代码块:

    driver.get("https://www.expedia.co.in/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#tab-flight-tab-hp"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flight-departing-hp-flight']//span[@class='label' and text()='Departing']//following::input[1]"))).send_keys("08/06/2019")
    returning = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flight-returning-hp-flight']//span[@class='label' and text()='Returning']//following::input[1]")))
    driver.execute_script("arguments[0].setAttribute('value','09/06/2019')", returning)
    
  • 浏览器快照:


需要对用户脚本进行一些更改

输入开始日期后,单击返回日期。然后返回空格以删除默认日期。下面是逻辑

driver.find_element(By.ID, "flight-departing-hp-flight").send_keys("07/06/2019")
ele = driver.find_element(By.ID, "flight-returning-hp-flight")
#click on return date field
ele.click()
# remove the default date(same as selected start date) by hitting backspace
length = len(ele.get_attribute('value'))
ele.send_keys(length * Keys.BACKSPACE)
#enter the return date
driver.find_element(By.XPATH, "//input[@id='flight-returning-hp-flight']").send_keys("10/06/2019")

你到底被困在哪里了?在我的脚本中,我输入了不同的到达和离开日期,但它选择了相同的到达和离开日期。这些定位器非常脆弱,使用JS设置值是对页面在UI中可能进行的任何检查的捷径,这不是一个最佳实践,更不用说是一个好的实践了。您应该像客户一样与UI交互,除非这是绝对不可能的。我得到了selenium.common.exceptions.Element ClickInterceptedException:Message:Element此时不可单击(182495)因为另一个元素掩盖了它,因为日期与搜索重叠button@Mrsreez在我的回答中,我处理了所有的
字段,没有一个元素具有属性
type=“submit”
。不确定您为什么会看到此错误。是的,JeffC
ele.clear()
至少没有使用OP使用的定位器清除值。