Selenium 如何定位嵌套的跨度元素定位器
如何仅定位包含以下代码中价格值的父跨度,定位器策略无关紧要:Selenium 如何定位嵌套的跨度元素定位器,selenium,xpath,css-selectors,Selenium,Xpath,Css Selectors,如何仅定位包含以下代码中价格值的父跨度,定位器策略无关紧要: <div class="price-box price-margin"> <p class="old-price"></p> <p class="special-price"> <span id="product-price-75254" class="price"> 56,90 €
<div class="price-box price-margin">
<p class="old-price"></p>
<p class="special-price">
<span id="product-price-75254" class="price">
56,90 €
<span class="steuerstern">*</span>
</span>
</p>
</div>
56,90 €
*
这里的问题不是选择器。但是文本功能
//p[@class="special-price"]/span[@class="price"]
这将选择节点,但selenium也将始终返回子节点的节点。在本例中,您要查找的是节点文本。这只能使用JavaScript完成。既然你没有提到一种语言,我就假设是python
elem = driver.find_element_by_xpath('//p[@class="special-price"]/span[@class="price"]')
price = driver.execute_script("return arguments[0].firstChild.textContent.trim();", elem)
print(price)
56,90 €
使用选择器,您可以执行以下操作:
".price-box span.price"
结果:
56,90 €
要在Chrome中测试xpath的正确性,可以使用
//span[@class="price"]/text()
由于您没有提到您使用的语言,下面是一个使用.getText()在nightwatchjs中使用selenium的示例
.getText()返回一个对象,实际文本是回调的值
var thetext='';
.getText('//span[@class="price"]' ,fucntion(result){
thetext=result.value();
})
由于您没有提到您正在使用的
Selenium
绑定,因此我将通过Java
绑定构造一个答案。在这里,我们将使用定制的xpath
来定位文本为56,90€
的节点,而不使用*
,如下所示:
WebElement ele = driver.findElement(By.xpath("//p[@class='special-price']/span[contains(@class,'price') and not(@class='steuerstern')]"));
//span[包含(,“56,90€”)
?该span的价格和id值不是固定的,它将根据产品选择而变化,需要是span//p[@class=“special price”]/span[@class=“price”]
的通用定位器,其中将包括子span class(),我不想考虑这一点,只是想重新定价(56,90欧元),而不是(56,90欧元)。您提供的定位器给了我(56,90欧元)*