如何解决在 Selenium、Python 中选择一个元素,而不是使用 XPath
我试图抓取一个网站,我只需要选择类“Slider__SliderWrapper-sc-143uniy-0 jrPmnS”的 div 中的 ul 元素,但是,由于有许多具有相同类的 div 标签,我必须只选择我需要的 ul 的唯一方法是查看 a 标签的 href,即 h2 中的标签。 我不能使用 xpath,因为 div 标签总是改变位置。
<div>
<h2><a class="slider-components__SectionLink-sc-1r2bduf-3 jchpWs" href="rightOne">Right!</a></h2>
<div class="Slider__SliderWrapper-sc-143uniy-0 jrPmnS">
<ul class="Slider__List-sc-143uniy-1 MTYOL">
the right ul
</ul>
</div>
</div>
<div>
<h2><a class="slider-components__SectionLink-sc-1r2bduf-3 jchpWs" href="wrongOne">Something else</a></h2>
<div class="Slider__SliderWrapper-sc-143uniy-0 jrPmnS">
<ul class="Slider__List-sc-143uniy-1 MTYOL">
the wrong ul
</ul>
</div>
</div>
我想过使用 css
选择器,但我不知道如何使用,有什么帮助吗?
解决方法
您绝对可以使用 xpath 访问 href 属性及其内容:
//a[contains(@href,'rightOne')]
对于 ul:
//h2/a[contains(@href,'rightOne')]/../following-sibling::div/ul
,
试试xpath
//a[@href='rightOne']/../following-sibling::div/ul
说明:
您不能使用 css_selector
或任何其他 locator
,因为您依赖于 a
标签并且您必须首先在 DOM 中向上遍历,我们为此使用 /..
,或者您可以使用 /parent::h2
和下一个 following-sibling
使用 /following-sibling::div
然后最后 ul
child
您无法使用 css 选择器获取父元素,因为这是不可能的。在这里查看Is there a CSS parent selector?
在您的情况下,您需要获取 a[href=rightOne]
的父项并获取以下兄弟项的 ul
。
通过 css,您可以使用以下定位器之一:
div:nth-child(1) .Slider__SliderWrapper-sc-143uniy-0.jrPmnS>.Slider__List-sc-143uniy-1.MTYOL
或
div:nth-child(1) .Slider__SliderWrapper-sc-143uniy-0.jrPmnS>ul
如果对选择器没有限制,我会选择其他两个答案中提出的任何 XPath。
但是,如果您使用诸如 BeautfulSoup 之类的库,则必须使用 css 选择器,因为它不支持 XPath。所以,使用我建议的那些。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。