如何基于现有XPath过滤掉class为a-row a-spacing-micro的子div元素?
Got it, let's sort out this XPath filtering task for you! You want to adjust your original expression to target only those parent divs that don't have a child div with the class a-row a-spacing-micro. Here are two solid ways to do it:
Approach 1: Exact class match (direct children)
Use the not() function to exclude elements that have a direct child div with the exact class string:
//div[@class='a-section a-spacing-none a-spacing-top-small' and not(div[@class='a-row a-spacing-micro'])]
Breakdown:
- Your original selector
//div[@class='a-section a-spacing-none a-spacing-top-small']grabs all the base elements you care about. - The
and not(div[@class='a-row a-spacing-micro'])clause adds a filter: only keep elements that do not have a direct child div with exactly that class.
Approach 2: Flexible class match (handles extra classes)
If the child div might have additional classes mixed in (like a-row a-spacing-micro some-other-class), use contains() to check for the presence of your target class substring:
//div[@class='a-section a-spacing-none a-spacing-top-small' and not(div[contains(@class, 'a-row a-spacing-micro')])]
Breakdown:
contains(@class, 'a-row a-spacing-micro')checks if the child's class attribute includes your target class string, which works even if there are other classes present.
Bonus: Check all descendants (not just direct children)
If you need to exclude elements that have the target div anywhere inside them (not just as a direct child), use .//div to look through all descendants:
//div[@class='a-section a-spacing-none a-spacing-top-small' and not(.//div[@class='a-row a-spacing-micro'])]
内容的提问来源于stack exchange,提问作者Kevin.a

