Selenium中特定格式日期升降序排序失败,求问题排查
解决Selenium中日期排序失效的问题
看起来你的代码没生效大概率是两个核心问题:日期格式解析不兼容所有序数后缀,加上XPath语法错误导致没正确获取到日期元素。咱们一步步排查修正:
问题1:XPath语法错误
你写的XPath .//[@id='pricedTransactionDiv']/div 是无效的——@id 前面必须指定节点选择器(比如*代表任意节点),正确的写法应该是:
List<WebElement> elementList= driver.findElements(By.xpath(".//*[@id='pricedTransactionDiv']/div"));
如果XPath不对,elementList可能是空的,后续的日期解析和排序自然毫无效果。
问题2:日期格式无法兼容所有序数后缀
你的日期字符串是「Monday 4th September 2017」这种格式,但SimpleDateFormat("EEE dd'th' MMMM yyyy")只能匹配带th后缀的日期,遇到1st、2nd、3rd的日期就会直接抛出ParseException(如果没捕获异常,这些日期会无法加入列表)。
解决方法是先移除日期中的序数后缀,再用标准格式解析:
- 用正则表达式把
st/nd/rd/th这些后缀去掉 - 改用
"EEE dd MMMM yyyy"格式解析处理后的字符串
修正后的完整代码
List<Date> listDates = new ArrayList<Date>(); // 修正XPath语法 List<WebElement> elementList= driver.findElements(By.xpath(".//*[@id='pricedTransactionDiv']/div")); // 匹配序数后缀的正则(兼容大小写) Pattern ordinalPattern = Pattern.compile("\\s*(st|nd|rd|th)\\s*", Pattern.CASE_INSENSITIVE); SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE dd MMMM yyyy"); // 设置时区避免解析偏差(可选但推荐) dateFormatter.setTimeZone(TimeZone.getDefault()); for(WebElement we: elementList) { try { String rawDate = we.getText().trim(); // 移除序数后缀 String cleanedDate = ordinalPattern.matcher(rawDate).replaceAll(""); Date parsedDate = dateFormatter.parse(cleanedDate); listDates.add(parsedDate); } catch (ParseException e) { // 捕获解析失败的情况,方便排查问题 System.err.println("Failed to parse date: " + we.getText()); e.printStackTrace(); } } test.log(LogStatus.INFO,"Results before applying sorting: "+listDates); System.out.println("Results before applying sorting: "+listDates); // 简化sortedList的创建方式 ArrayList<Date> sortedList = new ArrayList<>(listDates); // 升序排序 Collections.sort(sortedList); // 如果需要降序,替换成下面这行: // Collections.sort(sortedList, Collections.reverseOrder()); test.log(LogStatus.INFO,"Results after applying sorting: "+ sortedList); System.out.println("Results after applying sorting: "+sortedList);
额外提示
- 建议始终捕获
ParseException,这样能快速定位哪些日期格式异常,避免整个列表因为一个错误日期而失效 - 如果你的系统是多语言环境,记得给
SimpleDateFormat指定Locale,比如new SimpleDateFormat("EEE dd MMMM yyyy", Locale.ENGLISH),避免因为系统语言不同导致星期/月份解析失败
内容的提问来源于stack exchange,提问作者B123
相关产品推荐
相关产品推荐

