繁体   English   中英

如何使用Java搜索和突出显示某些单词?

[英]How to search and highlight certain word with Java?

是否可以使用ctrl+f类的方法在网页上搜索单词? 如何使用Java和Selenium搜索并突出显示网页上的某些单词? 例如,我需要在以下网页上搜索单词“ test”: https : //www.wedoqa.com/blog/我试图将答案混在一起,所以我编写了这样的代码:

WebElement matchedElement = driver.findElement(By.xpath("//*[text()='test']"));
            ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", matchedElement);
            if(driver.getPageSource().contains(matchedElement.toString())) {
                System.out.println("The page contains word: " + matchedElement.toString());
            } else {
                System.out.println("The page does not contains word asdfghjkl");
            }

但是,然后我得到了这样的错误:

*** Element info: {Using=xpath, value=//*[text()='test']}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:317)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:419)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:309)
    at test.Test1.main(Test1.java:59)

您可以使用JavaScript执行器突出显示匹配的元素。

样品:

//Partial Match of the word
WebElement matchedElement=driver.findElement(By.xpath("//*[contains(text(),'test')]"));
         (or)
//Exact Match of the word
WebElement matchedElement=driver.findElement(By.xpath("//*[text()='test']"));

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", matchedElement);

您可以通过页面源进行验证:

if(driver.getPageSource().contains("test")){
    System.out.println("The page contains word test");
    }

暂无
暂无

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

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