我有使用我的 IDE (intellij) 在本地运行的代码:
public class ConnectAndBrowse {
WebDriver driver;
private String m_baseUrl = "https://tinyurl.com/";
private String m_toShortenURL;
private ArrayList<String> tabs2;
public ConnectAndBrowse( String i_toShortenURL ) throws MalformedURLException {
setUp(i_toShortenURL);
}
private void setUp(String i_toShortenURL) throws MalformedURLException {
System.setProperty("webdriver.chrome.driver","./src/main/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
m_toShortenURL = i_toShortenURL;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public WebDriver browseToUrlWithShortLink() throws Exception {
driver.get(m_baseUrl);
driver.findElement(By.id("url")).click();
driver.findElement(By.id("url")).clear();
driver.findElement(By.id("url")).sendKeys(m_toShortenURL);
driver.findElement(By.id("submit")).click();
driver.findElement(By.linkText("Open in new window")).click();
return driver;
}
public String returnShortLink(WebDriver driver) {
String data = driver.findElement(By.xpath("//*[@id=\"contentcontainer\"]/div[2]/b")).getText();
return data;
}
}
这是我的主课:
public class ManagerService {
public static void main(String[] args) {
try {
FactoryHelper factoryHelper = new FactoryHelper();
Properties prop = factoryHelper.getPropFile();
String toShorten = prop.getProperty("defaultUrl");
ConnectAndBrowse connectAndBrowse = new ConnectAndBrowse(toShorten);
WebDriver driver=connectAndBrowse.browseToUrlWithShortLink();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我使用 maven (pom.xml) 只是为了下载专用驱动程序。 现在,我想从 Linux 上运行它,但我正在努力做到这一点。 知道我想添加到我的代码中的内容吗?
最佳答案
您的驱动程序版本必须根据 linux 版本进行更改。您可以下载 linux chromedriver 版本并将其放在资源文件夹中。您可以根据操作系统附加.exe 扩展名。
String chromedriverPath="./src/main/resources/drivers/chromedriver";
if(System.getProperty("os.name").toLowerCase().contains("win"))
chromedriverPath+=".exe";
System.setProperty("webdriver.chrome.driver",chromedriverPath);
WebDriver driver = new ChromeDriver();
或
您可以使用 Webdriver Manager 根据操作系统版本简单地以编程方式处理驱动程序下载
将这个 jar 依赖添加到你的 pom 中,
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
然后在启动驱动程序之前添加这一行。这将自动下载适当的驱动程序版本并在运行时设置路径变量。
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
关于java - 如何从 Linux 运行 selenium webdriver(目前在 Windows 中工作)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53175294/