有没有办法使用像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)
答案 0 :(得分:2)
您可以使用JavaScript Executor突出显示匹配的元素。
样品:
//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);
答案 1 :(得分:2)
You can verify it through page source:
if(driver.getPageSource().contains("test")){
System.out.println("The page contains word test");
}