在Selenium Webdriver中,如何在元素后面获取文本? [英] In Selenium Webdriver, how to get a text after an element?

查看:545
本文介绍了在Selenium Webdriver中,如何在元素后面获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个完全出现在特定元素之后的文本。请查看示例代码:

I would like to get a text that exactly comes after a specific element. Pleases look the sample code:

<div id="content-tab-submitter" class="">
    <h4>Sender</h4>
    <p> 
        <span class="screenHidden">Name: </span>
        submitter
        <br>

        <span class="screenHidden">E-mail address:</span>
        submitter@asd.com
        <br>

        <span class="screenHidden">Account: </span>
        asdas
        <br>
    </p>
</div>

我想获得正好在< span>之后出现的文字其中包含帐户。
使用此xpath:

I would like to get the text that comes exactly after <span> which contains "Account". By using this xpath:

//*[@id='content-tab-submitter']/p/span[contains(text(),'Account')]/following::text()

Java给了我一个错误,因为输出不是一个web元素,而是一个文本。因此,不可能使用findElement。

Java gives me an error, since the output is not a web element and it is a text. So, it is not possible to use findElement.

有任何想法如何以干净的方式获取此文本?我的意思是我不想得到所有文本:(在这种情况下)submitter\\\
submitter@asd.com\\\
asdas然后提取所需的文本。

Is there any idea how to get this text in a clean way? I mean I do not want to get all texts: (in this case) submitter\nsubmitter@asd.com\nasdas and then extract the desired text.

推荐答案

我认为在Account之后没有直接提取文本的方法:即直接引用text ='asdas'的xpath

HI i think there is no straight possible way to extract text just after Account: i.e a xpath which refers to text = 'asdas' directly

所以不要试图直接读取text ='asdas',而是尝试读取p标签中的每个文本并执行如下操作来提取标签。

so instead of trying to read exactly text = 'asdas' directly try to read every text in the p tag and perform operation like below to extract the tag.

WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/rajnish/Desktop/myText.html");

// xpath for talking complete text i.e all text inside every span tag that comes under p tag 
String MyCompleteText  = driver.findElement(By.xpath("//*[@id='content-tab-submitter']/p")).getText();

System.out.println("My Complete Text is : " + MyCompleteText);

// MyCompleteText outputs in console :
// My Complete Text is : Name: submitter
// E-mail address: submitter@asd.com
// Account: asdas

// now we have to split our MyCompleteText on the basis of Account:
// as we want text after Account: so do it like below

String[] mytext = MyCompleteText.split("Account:");
System.out.println("I am text after  Account: "+ mytext[1]);

并且输出将是这样的

My Complete Text is : Name: submitter
E-mail address: submitter@asd.com
Account: asdas
I am text after  Account:  asdas

希望这有助于你

这篇关于在Selenium Webdriver中,如何在元素后面获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆