在python硒中使用父级/同级查找元素

时间:2020-07-25 14:16:18

标签: python css selenium xpath web-scraping

我在python中使用硒来刮擦用angular js设计的网页,因此没有诸如id等元素的可靠标识符。我完全依赖CSS选择器(动态的)和xpath。

我有以下代码-

<div class="dpm-form-row ng-star-inserted">
<dpm-input-number class="flex-6">
<dpm-input-label>
<label>Fixed Rate</label>
</dpm-input-label>
<dpm-input-number-bare>
<input size="1" type="text" placeholder="" class="ng-pristine ng-valid ng-touched">
</dpm-input-number-bare>
</dpm-input-number>
<div class="flex-6">
</div>
</div>

基本上是一个称为“固定汇率”的标签,后跟一个输入文本框。我正试图抓住的那个盒子。

我已成功使用以下代码获取标签,但在使用父级/同级逻辑获取框时遇到了麻烦-

element = driver.find_element_by_xpath('//*[contains(text(),"Fixed Rate")]')

1 个答案:

答案 0 :(得分:2)

重新发布您的preceding问题。原始解决方案:

//input[@class="ng-pristine ng-valid ng-touched"][../preceding-sibling::dpm-input-label[1]/label[.="Fixed Rate"]]

使用following-sibling轴的3个XPath:

//dpm-input-label[label[.="Fixed Rate"]]/following-sibling::dpm-input-number-bare[1]/input
//dpm-input-label[label[contains(.,"Fixed Rate")]]/following-sibling::dpm-input-number-bare[1]/input
//dpm-input-label[contains(.,"Fixed Rate")]/following-sibling::dpm-input-number-bare[1]/input

3个使用preceding-sibling轴并为contains元素使用多个input的XPath:

//input[contains(@class,"ng-pristine") and contains(@class,"ng-valid") and contains(@class,"ng-touched")][../preceding-sibling::dpm-input-label[1]/label[.="Fixed Rate"]]
//input[contains(@class,"ng-pristine") and contains(@class,"ng-valid") and contains(@class,"ng-touched")][../preceding-sibling::dpm-input-label[1]/label[contains(.,"Fixed Rate")]]
//input[contains(@class,"ng-pristine") and contains(@class,"ng-valid") and contains(@class,"ng-touched")][../preceding-sibling::dpm-input-label[1][contains(.,"Fixed Rate")]]

使用preceding轴的4个XPath:

//input[@class="ng-pristine ng-valid ng-touched"][preceding::label[1][.="Fixed Rate"]]
//input[@class="ng-pristine ng-valid ng-touched"][preceding::label[1][contains(.,"Fixed Rate")]]
//input[contains(@class,"ng-pristine") and contains(@class,"ng-valid") and contains(@class,"ng-touched")][preceding::label[1][.="Fixed Rate"]]
//input[contains(@class,"ng-pristine") and contains(@class,"ng-valid") and contains(@class,"ng-touched")][preceding::label[1][contains(.,"Fixed Rate")]]