linux 的环境准备
安装 google-chrome
yum install https:
下载 Chromedriver
地址:http:
下载后放到根目录,注意要给 chromedriver 可执行权限:chmod 777 /chromedriver
windows 的环境准备
安装 google-chrome 浏览器
下载 Chromedriver
地址:http:
JAVA Maven
maven 导入包
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
工具类例子
package c.o.v;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class YXMUtil {
public static void main(String[] args) {
get("https://mall.q-gp.com/share/product?skuNo=366936136878081");
}
public static Map<String, String> get(String url) {
System.setProperty("webdriver.chrome.driver", "/chromedriver.exe");
WebDriver driver;
ChromeOptions option = new ChromeOptions();
option.addArguments("headless");
option.addArguments("no-sandbox");
option.setExperimentalOptions("useAutomationExtension", false);
option.setExperimentalOptions("excludeSwitches", Collections.singletonList("enable-automation"));
driver = new ChromeDriver(option);
driver.get(url);
String title = "";
String num = "";
String img = "";
long time = System.currentTimeMillis();
while (StringUtils.isEmpty(img) || StringUtils.isEmpty(title) || StringUtils.isEmpty(num)) {
img = driver.findElement(By.className("cr-image--img")).getAttribute("src");
title = driver.findElement(By.className("title")).getText();
num = driver.findElement(By.className("num")).getText();
if (System.currentTimeMillis() - time > 5000) {
System.out.println("获取超时,已结束");
driver.quit();
return null;
}
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("标题:" + title);
System.out.println("价格:" + num);
System.out.println("图片:" + img);
driver.quit();
Map<String, String> map = new HashMap();
map.put("title", title);
map.put("num", num);
map.put("img", img);
return map;
}
}
|