我需要找到报告链接。但是链接本身的信息过于笼统而无法表征,但其下一个兄弟是一个span元素,其文本可以识别span元素。所以我决定首先找到span元素,然后通过xpath的previous-siblings方式使用span元素来查找link元素。
我想知道是否有更好的方法可以做到这一点?
以下是显示其定义和关系的HTML细分:
<td style="font-size: 12px;" width="70%">
<a href="/reports/4981/"><span><b style="color: #3366FF; text-decoration: underline;">Cases Report</b></span></a>
<span style="color: #888;">requested on Tue, Mar 20, 2018 at 9:14 p.m. — CSV — <b><i>Ready to download</i></b></span>
</td>
这是我尝试的实现(尚未完全正常工作):
span_xpath = '//span[contains(., "Ready to download")]'
# . stands for text in the current node regardless of in bold or not
relative_report_link_xpath = '//preceding-sibling::a[contains(@href, "/reports/")]'
span_list = driver.find_elements_by_xpath(span_xpath)
# There might be multiple such links and spans
# I will have logic to select the desired one
# based on the timestamp in the span.
# For brevity, I just hard code the selection for now:
found_span = span_list[0] # will be logic involving timestamp
found_span.click() # make the span as the current node
driver.find_element_by_xpath(relative_report_link_xpath).click()
例如,我真的不想点击span元素,只是为了将span作为当前节点,以便我可以通过前面的兄弟来导航。我希望知道一个不那么干扰的&#34;将Web元素设置为当前节点而不单击它的实现。 (点击一个span元素,在这种情况下,也许没问题,但如果它是另一个链接的一部分,那么行为将不是我想要的。)
上述实施不起作用。 relative_report_link_xpath会找到另一个(链接)元素,它根本不是所点击的跨度的兄弟。
我在Firefox / Python中使用Selenium。
答案 0 :(得分:0)
以下是使用xpath的解决方案:
span_xpath = '//span[contains(., "Ready to download")]'
# . stands for text in the current node regardless of in bold or not
span_list = driver.find_elements_by_xpath(span_xpath)
# There might be multiple such links and spans
# I will have logic to select the desired one
# based on the timestamp in the span.
# For brevity, I just hard code the selection for now:
found_index = 0
report_link_xpath = \
'//span[contains(., "Ready to download")]//preceding-sibling::a[contains(@href, "/reports/")]' + \
'[' + str(found_index + 1) + ']'
# '//span[contains(., "Ready to download")]//preceding-sibling::a[contains(@href, "/reports/")][1]'
driver.find_element_by_xpath(report_link_xpath).click()
它按预期工作。
故事的寓意是,就网络元素位置而言,Selenium在xpath之上提供了最小的包装器,所有操作都应该通过xpath完成。