如何获取包含在<p>标记下的段落中的文本的CSS选择器

时间:2017-12-04 17:43:44

标签: css xpath selenium-webdriver

我试图使用Xpath选择器(Xpath:html / body / p [2] / text()[3])捕获邮件段落中的URL。我无法获得正确的css选择器,但是使用Xpath,我在执行Selenium webdriver测试时遇到如下所示的错误。

<body>
<p>Dear EmailTest user,</p>
<p>
Your profile on the Swwebsite has been successfully created.
<br/>
To begin, click on the link below. You will be prompted to create a password during the login process.
<br/>
https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd
<br/>
After creating your password, you will be able to access your application with the below username:
<br/>
User Name emailuser_test
<br/>
</p>

获得以下错误:

  

com.ibm.automation.wtf.driver.DriverException:TypeError:Window.getComputedStyle的参数1未实现接口元素。
  构建信息:版本:'3.5.2',修订版:'10229a9',时间:'2017-08-21T17:29:55.15Z'

在互联网上进行一些搜索时,它似乎是一个带有CSS的Firefox问题。有人可以帮我解决这个问题或获得一个合适的CSS选择器来捕获邮件中的URL

  

系统信息:主机:'IBM345-R902EWZ3',ip:'9.162.252.164',os.name:'Windows 7',os.arch:'amd64',os.version:'6.1',java.version :'1.8.0_121'
  驱动程序信息:org.openqa.selenium.firefox.FirefoxDriver

2 个答案:

答案 0 :(得分:1)

首先使用<p>方法在getText()标记下获取整个邮件正文,然后使用Java String操作捕获URL,如split / substring / indexOf方法。

使用如下的cssSelector:

String mailBody = driver.findElement(By.cssSelector("body > p:nth-child(2)")).getText();

现在解析字符串以捕获URL。

例如:

String[] temp = mailBody.split("\n");
String url = temp[2];
System.out.println(url);

或者

int startIndex = mailBody.indexOf("https");
int endIndex = mailBody.indexOf("After creating your password");
String url = mailBody.substring(startIndex, endIndex - 1);
System.out.println(url);

或者您可以使用任何字符串操作(或正则表达式)从mailBody字符串中搜索URL

另一个尝试:
您还可以使用xpath html/body/p[2]获取整个邮件正文,然后解析该字符串。

答案 1 :(得分:0)

Java:

要捕获 URL ,我们会首先捕获第二个 <p> 标记下的总文字,然后用{{3分割一次在右侧包含 https ,然后再次使用positive lookaround将其拆分,以在右侧包含 After 手侧,最后打印剩余的左手部分。为此,您可以使用以下代码块:

String myText = driver.findElement(By.xpath("//body//following::p[2]")).getAttribute("innerHTML");
String[] textParts = myText.split("(?=https)");
String mySubtext = textParts[1];
String[] subparts = mySubtext.split("(?=After)");
String text = subparts[0];
System.out.println(text);

这会在我的控制台上打印以下内容:

https://test.website.com/one/portal/$swweb/?uri=emailuser-125633uu3d-452iekdkd 
相关问题