有人可以指导我如何在 selenium python 中从 expedia.com 上的日期选择器中选择日期范围吗?
例如:前往 expedia/flights 单击“日期”并选择当天到接下来的 7 天。
driver = webdriver.Chrome()
ac = ActionChains(driver)
driver.implicitly_wait(10)
driver.get("https://www.expedia.com/Flights")
dates_btn = driver.find_element(By.XPATH,'//\*\[@id="FlightSearchForm_ROUND_TRIP"\]/div/div\[2\]')
ac.click(dates_btn).perform()
calendar = driver.find_element(By.XPATH,'//\*\[@id="FlightSearchForm_ROUND_TRIP"\]/div/div\[2\]/div/section')
ac.move_to_element(calendar).perform()
我尝试测试选择右侧日历顶部的月份和年份,但遇到无法找到元素的错误
right_month_year = driver.find_element(By.XPATH,'//\*\[@id="FlightSearchForm_ROUND_TRIP"\]/div/div\[2\]/div/div/div/div\[2\]/div/div\[1\]/div\[2\]/div\[2\]/h2')
print(month_year.text)
这是工作代码,并对代码中的每一行进行了解释:
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.expedia.com/Flights")
driver.maximize_window()
wait = WebDriverWait(driver, 10)
# Click on date picker button
wait.until(EC.element_to_be_clickable((By.ID, "date_form_field-btn"))).click()
# By default calendar opens up next month(Nov). Below line will click on back button to go to Oct month
wait.until(EC.element_to_be_clickable((By.XPATH, "(//button[@data-stid='date-picker-paging'])[1]"))).click()
# Click on Oct 23rd. Change the XPath if you want to select some other day
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@aria-label,'Oct 23, 2024')]"))).click()
# Click on Oct 30th. Change the XPath if you want to select some other day
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@aria-label,'Oct 30, 2024')]"))).click()
# Click on 'Done' button
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@data-stid='apply-date-picker']"))).click()
time.sleep(20)
结果: