Selenium操作booking.com日历无法选中并打印右侧月份问题求助
问题根因
你调用driver.findElement(By.className("bui-calendar__month"))时,Selenium默认只会返回DOM结构中第一个匹配该类名的元素,也就是日历的左侧月份。当目标月份是可选范围的最后一个月(2022年11月)时,它仅会出现在右侧面板,左侧面板的月份不符合你的匹配条件,导致循环会持续点击下一页直到按钮失效,自然无法定位到右侧的目标月份。
修正方案
每次翻页后同时读取左右两个月份的信息,只要任意一个匹配目标年月就停止翻页,再根据目标月份所在的面板定位日期。
修正后完整代码
package HandlingCalendars; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class BookingDotCom { public static void main(String[] args) { String bookingdate = "21-November-2022"; String[] temp = bookingdate.split("-"); String targetDate = temp[0]; String targetMonth = temp[1]; String targetYear = temp[2]; System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.get("https://www.booking.com/"); driver.findElement(By.xpath("//div[contains(@data-mode,'checkin')]")).click(); boolean found = false; while (!found) { // 同时获取左右两个月份元素 List<WebElement> monthElements = driver.findElements(By.className("bui-calendar__month")); // 遍历两个月份检查是否匹配目标 for (WebElement monthEl : monthElements) { String[] yearMonth = monthEl.getText().split(" "); String currentMonth = yearMonth[0]; String currentYear = yearMonth[1]; if (currentYear.equals(targetYear) && currentMonth.equalsIgnoreCase(targetMonth)) { found = true; System.out.println("找到目标月份:" + currentMonth + " " + currentYear); // 对应面板下选中目标日期 WebElement calendarPanel = monthEl.findElement(By.xpath("./ancestor::div[contains(@class,'bui-calendar__wrapper')]")); calendarPanel.findElement(By.xpath(".//span[text()='"+targetDate+"']")).click(); break; } } // 没找到就点下一页 if (!found) { driver.findElement(By.xpath("//div[@class='bui-calendar__control bui-calendar__control--next']")).click(); } } } }
内容的提问来源于stack exchange,提问作者Exuberant Singh
相关产品推荐
相关产品推荐

