【问题标题】:Select an element in Selenium, Python, not by using XPath在 Selenium、Python 中选择一个元素,而不是使用 XPath
【发布时间】:2021-08-16 00:51:36
【问题描述】:

我试图抓取一个网站,我只需要选择类“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 选择器,但我不知道如何使用,有什么帮助吗?

【问题讨论】:

  • 查看这些链接,可能会有所帮助link1 link2 & link3
  • 你可以使用 xpath。

标签: python css selenium web-scraping selector


【解决方案1】:

您绝对可以使用 xpath 访问 href 属性及其内容:

//a[contains(@href,'rightOne')]

对于 ul:

//h2/a[contains(@href,'rightOne')]/../following-sibling::div/ul

【讨论】:

    【解决方案2】:

    试试xpath

    //a[@href='rightOne']/../following-sibling::div/ul
    

    说明:

    你不能使用css_selector或任何其他locator,因为你依赖于a标签,你必须先在DOM中向上遍历,我们使用/..,或者你可以使用/parent::h2下一个following-sibling 使用/following-sibling::div,最后是ul child

    【讨论】:

    • 但是这样你选择a标签,我需要一个div的ul,chid,靠近包含那个标签的h2。
    • @CalenBrow :查看更新的答案!
    【解决方案3】:

    您无法使用 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。所以,使用我建议的那些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2019-03-10
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多