【发布时间】:2018-07-24 01:50:07
【问题描述】:
preceding-sibling 和 following-sibling 是明确选择兄弟姐妹的唯一选项吗?
标记的简化版本
<ui-view>
<descendant> <!-- 1 -->
<descendant> <!-- 2 -->
<descendant> <!-- 3 -->
<descendant> <!-- 4 -->
<descendant> <!-- 5 -->
<sibling>
<child></child> <!-- comments_author -->
<child></child> <!-- comments_timestamp -->
</sibling>
<sibling></sibling> <!-- comment (in comments_comment) -->
脚本
# 1. Select All Comment Threads
comments_threads = browser.find_elements_by_xpath('//ui-view//div[@class="commentLayout"]')
for thread in comments_threads:
# 2. Select All Comments in Each Thread
comments_comment = comments_threads.find_elements_by_xpath('./div[contains(@class, "commentLayout-text")]')
for comment in comments_comment:
# 3. Select Author of Each Comment
# comments_author = comments_threads.find_element_by_xpath('./*[contains(@class, "commentLayout-account")]')
# 4. Select Timestamp of Each Comment
# comments_timestamp = comments_threads.find_element_by_xpath('./span[contains(@class, "commentNote")]')
问题是必须针对嵌套循环的每个 comment 项选择 3 和 4,我希望我的代码尽可能灵活。
选择任何同级来匹配所需节点将比使用preceding-sibling 匹配所需节点灵活得多。
一种解决方案是选择父节点,然后选择任何匹配特定条件的子节点,但如果可能的话,使用任何兄弟节点作为选择器肯定会更灵活,甚至更有效。
不能选择所有个兄弟姐妹吗?
【问题讨论】:
-
发布代码从不使用
preceding-sibling或following-sibling,但询问如何获取所有兄弟姐妹相当令人困惑。如果您发布示例标记并根据标记中的某些不变量解释您尝试选择的内容,您的问题会更清楚。 -
这听起来像X-Y problem。与其寻求解决问题的帮助,不如编辑您的问题并询问实际问题。你想做什么?
-
这就是原因,我问你而不是寻求帮助来解决问题,编辑你的问题并询问实际问题。你想做什么?您要自动化的手动步骤是什么?
-
@Anthony 这里没有责备游戏。您的问题不清楚,也没有任何代码试验。见:How to create a Minimal, Complete, and Verifiable example.
-
XPath 中没有
preceding-and-following-siblings或siblings轴,也不需要它们。您拒绝提供实际的minimal reproducible example 而不是草图,这使我们无法为您提供更详细的答案。正如@DebanjanB 所建议的那样,您的问题的结构确实类似于 XY 问题。如果您的问题只是有一个siblings轴,那么简单的答案是没有。您寻求的“其他选项”将取决于您的实际标记的细节,而不是它的抽象草图,以及您的实际目标,而不是根据感知的最佳方法表达的方法。