通过XPath查找具有多个元素,单独的行

时间:2018-12-05 23:35:07

标签: c# selenium-webdriver

我试图根据一个元素是否在两个不同的位置包含文本来查找一个元素,抱歉,由于缺乏术语,我对HTML不太熟悉。这是网站上的HTML:

<article>
    <div class="inner-article">
        <a style="height:150px;" href="/shop/tops-sweaters/tx74hqf5v/lmfhiu5p8">
            <img width="150" height="150" src="//assets.supremenewyork.com/161584/vi/-tUn9HN7n-0.jpg" alt=" tun9hn7n 0">
        </a>
        <h1>
            <a class="name-link" href="/shop/tops-sweaters/tx74hqf5v/lmfhiu5p8">Fade Stripe L/S Top</a>
        </h1>
        <p>
            <a class="name-link" href="/shop/tops-sweaters/tx74hqf5v/lmfhiu5p8">Brown</a>
        </p>
    </div>
</article>

分别搜索元素是可行的,但是当我尝试使用“ and”时,它是行不通的。这是有效的方法:

driver[task].FindElement(By.XPath($"//a[contains(text(),'Fade')]")).Click();
driver[task].FindElement(By.XPath($"//a[contains(text(),'Brown')]")).Click();

我尝试过的事情:

driver[task].FindElement(By.XPath($"//a[contains(text(),'Fade') and //a[contains(text(),'Brown')]")).Click();

没有运气,请帮助,谢谢!我正在使用c#和Selenium:)

2 个答案:

答案 0 :(得分:1)

在这种情况下,我要做的是找到一个“ anchor”元素,然后找到作为该锚点子元素的两个(或多个)元素。

为匹配您发布的HTML,我将寻找“淡色条纹L / S上衣”和“棕色”。我将使用ARTICLE标签作为锚点。

我通常从做一些简单的事情开始,然后在上面做基础。让我们在A锚点下的ARTICLE标签中找到“淡色条纹L / S顶部”文本。

//article//a[.='Fade Stripe L/S Top']
^ double slash means at any level
  ^ the ARTICLE tag
         ^ at any level below that
           ^ an A tag
            ^ that contains the exact text "Fade Stripe L/S Top"

现在让我们做同样的事情,只是“棕色”文字

//article//a[.='Brown']

真的很简单...从您的帖子中,我假设您可以自己完成此操作,或者至少一直在关注。现在,让我们稍微翻转一下它,并使用ARTICLE作为锚点...找到一个ARTICLE标签,该标签的后代A标签包含“布朗”。

//article[.//a[.='Brown']]

这将返回ARTICLE标签而不是A标签,因为

[.//a[.='Brown']]
 ^ start looking at the tag previously specified
  ^ at any level
    ^ the rest you already know

表示它是ARTICLE标记的属性(包含在[] s中)。现在,我们有了ARTICLE,其中包含带有文本“ Brown”的链接。现在,我们只需要确保它还包含带有文本“ Fade Stripe L / S Top”的链接并返回该A标签即可。

//article[.//a[.='Brown']]//a[.='Fade Stripe L/S Top']
^ this first part is from above
                          ^ this is where the new stuff starts but it should be recognizable

希望这是有道理的。基本上,我们找到包含链接之一的ARTICLE标签(使用[.//tag[property]]语法),然后找到后代//tag[property],依此类推。

只是为了进一步扩展它...我们可以寻找任意数量的属性。希望这可以帮助您更好地了解模式。

//article [.//a[.='Brown']] [.//a[.='Text2']] [.//a[.='Text3']] //a[.='Fade Stripe L/S Top']

我在属性之间添加了空格以供强调。

//article [.//a  [.='Brown']] //a  [.='Fade Stripe L/S Top']
//tag     [.//tag[property ]] //tag[property]

答案 1 :(得分:0)

我认为您需要做什么,或者

a=> driver[task].FindElement(By.XPath($"//a[contains(text(),'Zip')]")).Click();
b=> driver[task].FindElement(By.XPath($"//a[contains(text(),'Brown')]")).Click();

不是'a'和'b'而是'a'或'b'