如何用XPath实现jQuery nextUntil功能选取两分类间元素
XPath实现nextUntil效果的解决方案
XPath完全可以实现你要的区间筛选效果,不需要额外编写循环终止逻辑,通过节点关系条件限制即可等效jQuery的nextUntil方法。你之前的写法没有添加下一个分类节点的终止条件,所以会选中当前分类之后所有的div元素。
核心实现逻辑
要选中两个.category节点之间的所有子项,核心是通过preceding-sibling轴统计前置分类节点的数量,将元素归属到对应的分类区间:
- 属于第N个分类的子项,前置
.category节点的数量一定等于N - 过滤掉本身是
.category的节点,只保留普通子项
具体XPath写法
按分类文本精准匹配
# 选取分类一到分类二之间的所有子项 //div[@class='category' and text()='Category one']/following-sibling::div[not(@class='category') and count(preceding-sibling::div[@class='category']) = 1] # 选取分类二之后的所有子项(如果是最后一个分类也适用) //div[@class='category' and text()='Category two']/following-sibling::div[not(@class='category') and count(preceding-sibling::div[@class='category']) = 2]
按索引遍历所有分类的配套代码(Python Selenium示例)
# 获取所有分类节点 category_list = driver.find_elements_by_xpath('.//div[@class="category"]') # 遍历每个分类,提取对应子项 for cate_index, category in enumerate(category_list, start=1): # 直接通过XPath筛选当前分类对应的区间子项 current_items = category.find_elements_by_xpath( f'./following-sibling::div[not(@class="category") and count(preceding-sibling::div[@class="category"]) = {cate_index}]' ) # 处理当前分类的子项 for item in current_items: print(item.text)
语法说明
following-sibling::div:只选取当前节点同级的后续div元素,避免误选其他层级的节点not(@class='category'):排除其他分类节点本身count(preceding-sibling::div[@class='category']) = N:限制子项仅属于第N个分类的区间,自动在下一个分类节点处停止匹配
内容的提问来源于stack exchange,提问作者Nahashon Muriithi
相关产品推荐
相关产品推荐

