用selenium去用xpath查找元素
现在对于同一个元素,有两种情况
父元素div和子元素span之间没有其他元素:
<div class=”price-text srv_price”>
<span aria-label=”Price” class=”x-hidden-focus”>$799.00</span>
</div>
父元素div和子元素span之间,有另外一层的div:
<div class=”price-text srv_price”>
<s class=”srv_saleprice” aria-label=”Full price was $1,699.00″>$1,699.00</s>
<span> </span>
<div class=”price-disclaimer “>
<span aria-label=”Now $1,299.00″ class=”x-hidden-focus”>$1,299.00</span>
</div>
</div>
而selenium中如果只用一个xpath去匹配,无法同时匹配另外一种情况,就会报异常
现在希望能找到看看xpath中,是否支持同时满足两种的条件的方法
xpath multiple condition
xml – XPath with multiple conditions – Stack Overflow
How to Use multiple conditions in Xpath? – Stack Overflow
都是同一个路径中,多个属性之类的匹配,不是我要的
Select on multiple criteria with XPath – Stack Overflow
union,或,是我要的
【总结】
通过竖线|把两种xpath规则“或”起来:
把:
<code>//div[@class="price-text srv_price"]/span[@aria-label] </code>
和
<code>div[@class="price-text srv_price"]/div[contains(@class, "price-disclaimer")]/span[@aria-label] </code>
或起来:
<code>multipleXpathRule = '//div[@class="price-text srv_price"]/span[@aria-label] | //div[@class="price-text srv_price"]/div[contains(@class, "price-disclaimer")]/span[@aria-label]' </code>
即可同时匹配到:
<code><div class="price-text srv_price"> <span aria-label="Price" class="x-hidden-focus">$799.00</span> </div> </code>
或:
<code><div class="price-text srv_price"> <s class="srv_saleprice" aria-label="Full price was $1,699.00">$1,699.00</s> <span>&nbsp;</span> <div class="price-disclaimer "> <span aria-label="Now $1,299.00" class="x-hidden-focus">$1,299.00</span> </div> </div> </code>
另外,后来想到了:
对于此处的html,其实如果写成单个xpath:
<code>priceSpanElement = driver.find_element_by_xpath('//div[@class="price-text srv_price"]//span[@aria-label]') </code>
也是可以都匹配到的。