简体   繁体   English

Selenium xPath-通过部分文本定位元素

[英]Selenium xPath - Locating element by partial text

I have following HTML code of my Page. 我的网页有以下HTML代码。

<div class="views-field-wbapi-data-value-2014 wbapi-data-value wbapi-data-value-first">
    <span class="field-content">
        <span>
            <a href="http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph">
                <span class="human-readable"></span>
            </a>

And

<div class="views-field-wbapi-data-value-2014 wbapi-data-value wbapi-data-value-first">
    <span class="field-content">
        <span>
            <a href="http://data.worldbank.org/indicator/NY.GDP.MKTP.CD/countries/SC?display=graph">
                <span class="human-readable">91,400</span>
            </a>

I have come up with the following xpath to locate <span class="human-readable"></span> of the first HTML code block. 我想出了以下xpath来定位第一个HTML代码块的<span class="human-readable"></span> human- <span class="human-readable"></span>

//div[@class='views-field-wbapi-data-value-2014 wbapi-data-value wbapi-data-value-first']/span/span/a/span

But when I run the above xpath, it gives me 2 matching nodes which is clear to me from the HTML code. 但是,当我运行上面的xpath时,它给了我2个匹配的节点,这从HTML代码中可以很明显地看出来。 There is a slight difference in href parameter of tag 'a'. 标签“ a”的href参数略有不同。 The first code block contains "SP.POP.TOTL" and the second block contains "NY.GDP.MKTP.CD". 第一个代码块包含“ SP.POP.TOTL”,第二个代码块包含“ NY.GDP.MKTP.CD”。

Is there any way I can access partial text of href parameter of 'a' tag and use it in my xpath to differentiate between the 2 blocks? 有什么方法可以访问'a'标签的href参数的部分文本,并在我的xpath中使用它来区分2个块?

Note: I cannot use the following xpath: //a[@href='http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph']/span because I am running a for loop on 40 different countries and every time text after '/countries/' , "SC" , changes. 注意:我无法使用以下xpath:// //a[@href='http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph']/span [ //a[@href='http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph']/span : //a[@href='http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph']/span ]/ //a[@href='http://data.worldbank.org/indicator/SP.POP.TOTL/countries/SC?display=graph']/span因为我正在运行在40个不同国家/地区的for循环,并且每次'/ countries /'后的文本“ SC”更改时。 So I have to use partial text , independent of the country prefix. 因此,我必须使用不依赖国家/地区前缀的部分文本。

use this as cssSelector: 将此用作cssSelector:

a[href*='SP.POP.TOTL']>span.human-readable

use this in code like below: 在下面的代码中使用此代码:

driver.findElement(By.cssSelector("a[href*='SP.POP.TOTL']>span.human-readable"));

Have you tried using the contains function? 您是否尝试过使用contains函数? You could try adding the following. 您可以尝试添加以下内容。

/a[contains(@href,'SP.POP.TOTL')]/span

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM