1. 程式人生 > >模擬瀏覽器自動化測試工具Selenium之六設定代理篇

模擬瀏覽器自動化測試工具Selenium之六設定代理篇

在使用Selenium自動化測試時,如果需要設定代理訪問網路時,可以參考如下程式碼:

package com.test;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class EBayCom {
	public static void main(String[] args) {
		System.getProperties().setProperty("webdriver.chrome.driver","D:\\dev\\workspace\\ocweb\\libs\\chromedriver.exe");	
		WebDriver webDriver = new ChromeDriver();
		//設定代理
		String proxyIpAndPort= "ip:post";
		DesiredCapabilities cap = new DesiredCapabilities();
		Proxy proxy=new Proxy();
		proxy.setHttpProxy(proxyIpAndPort).setFtpProxy(proxyIpAndPort).setSslProxy(proxyIpAndPort);
		cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
		cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
		System.setProperty("http.nonProxyHosts", "localhost");
		cap.setCapability(CapabilityType.PROXY, proxy);
		//訪問網址
		try {
			webDriver.get("IP");//訪問網址
			//標題
			WebElement eleItemTitle = webDriver.findElement(By.id("itemTitle")); 		
			String txtItemTitle=eleItemTitle.getText();
			System.out.println(txtItemTitle); 
		}catch (Exception e) { System.err.println( "Exception: " + e );}
		webDriver.close();
        	webDriver.quit();
	}
}