最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Selenium中使用xpath去查找元素时是否可以设置两种规则

selenium crifan 3665浏览 0评论

用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>&nbsp;</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,或,是我要的

【已解决】selenium的Python如何获取元素的文本

【总结】

通过竖线|把两种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>&lt;div class="price-text srv_price"&gt;
            &lt;span aria-label="Price" class="x-hidden-focus"&gt;$799.00&lt;/span&gt;
        &lt;/div&gt;
</code>

或:

<code>&lt;div class="price-text srv_price"&gt;
            &lt;s class="srv_saleprice" aria-label="Full price was $1,699.00"&gt;$1,699.00&lt;/s&gt;
            &lt;span&gt;&amp;nbsp;&lt;/span&gt;
            &lt;div class="price-disclaimer "&gt;
                &lt;span aria-label="Now $1,299.00" class="x-hidden-focus"&gt;$1,299.00&lt;/span&gt;  
            &lt;/div&gt;
        &lt;/div&gt;
</code>

另外,后来想到了:

对于此处的html,其实如果写成单个xpath:

<code>priceSpanElement = driver.find_element_by_xpath('//div[@class="price-text srv_price"]//span[@aria-label]')
</code>

也是可以都匹配到的。

转载请注明:在路上 » 【已解决】Selenium中使用xpath去查找元素时是否可以设置两种规则

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.165 seconds, using 22.05MB memory