![](/img/trans.png)
[英]unable to select an element using xpath in selenium and python
[英]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.