本文介绍Actions类下第二个功能,划取字段。我之前做过一个项目,需要在一堆log字符中随机划取一段文字,然后右键选择摘取功能。这篇,就介绍划取字段这个功能,直接看下面的脚本。
package lessons;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class MyClass {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", ".\\Tools\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("https://www.baidu.com/duty/");
//定义第一段文字
WebElement Sting_Sected = driver.findElement(By.xpath("//*/div[@class='dwri_bule']/table/tbody/tr/td/p"));
//定义第二段文字
WebElement String_Second = driver.findElement(By.xpath("//*/div[@class='dwri_bule']/table/tbody/tr/td/ul/li[1]"));
Actions action = new Actions(driver);
action.clickAndHold(Sting_Sected).moveToElement(String_Second).perform();
action.release();
}
}
在上面代码里定义了两个元素element1 和element2,element1是定位在最顶端的那段文字,element2是定义下面第一小点的文字。功能原理就是,找到顶端那个文字,然后按下鼠标不动,移动到element2然后释放鼠标,在实际过程中,会随机划取element1到element2直接的文字,划多少文字,没法确定。
我这边运行效果