繁体   English   中英

Select Selenium、Python 中的一个元素,而不是使用 ZB6454D4986313710A1891ZED1CEA

[英]Select an element in Selenium, Python, not by using XPath

I was trying to scrape a website, and I need to select only the ul element inside the div with a class "Slider__SliderWrapper-sc-143uniy-0 jrPmnS", however, since there are many div tags with the same class, the only way我必须 select 只是我需要的 ul 是通过查看 h2 内的 a 标签的 href。 我不能使用 xpath,因为 div 标签总是改变 position。

<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 选择器获取父元素,因为这是不可能的。 检查这里是否有 CSS 父选择器?

在您的情况下,您需要获取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

如果对选择器没有限制,我会 select 在其他两个答案中提出的任何 XPaths。

但是,如果您使用BeautfulSoup等库,则必须使用 css 选择器,因为它不支持 XPath。 所以,使用我建议的那些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM