我用 python 结合 selenium 编写了一个脚本,用于单击网页中名为 follow
的按钮。问题是,当我尝试使用两个不同的选择器时,它们都可以单击同一个按钮。
第一个选择器:
"a[href$='/follow']"
第二个:
"a[href$='/follow'] > button"
相关html部分:
<div class="nZSzR">
<h1 class="fDxYl">
some royal personality
</h1>
<span class="VerifiedBadge" title="Verified">
Verified
</span>
<a class="BY3EC" href="/accounts/follow" rel="nofollow">
<button class="L3NKy" type="button">
Follow
</button>
</a>
</div>
我应该坚持哪种方式,为什么?
最佳答案
米修,
您拥有的css选择器
a[href$='/follow']
,用href<表示 anchor 标记以 /follow
结尾的/strong> 属性
第二个 a[href$='/follow'] > 按钮
,定位父级为 anchor 标记的按钮。
因此,您可以在第二个 css 中清楚地看到,存在按钮的依赖关系。因此,如果您可以先进行,那么您应该优先考虑它。
对于这个HTML:
<a class="BY3EC" href="/accounts/follow" rel="nofollow">
<button class="L3NKy" type="button">
Follow
</button>
</a>
显然第一个 css 的依赖性较小。
如果它是 anchor 标记,那么答案就不需要css选择器。
您可以直接使用LINK_TEXT
或PARTIAL_LINK_TEXT
示例代码:
continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')
欲了解更多信息,请访问此官方 link .
关于python - 无法区分用于执行一项特定操作的两个选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600815/