selenium自动测试抓取股票信息

主要功能:
1、启动浏览器
2、浏览器访问URL
3、模拟点击链接
4、selenium抓取新页面中的内容
准备工作:
1、谷歌浏览器
2、谷歌浏览器驱动点击[下载驱动 (访问密码:2604)]
https://url87.ctfile.com/f/18103887-517938061-890ce7
(访问密码:2604)
3、代码[下载源码地址 (访问密码:2604)]
https://url87.ctfile.com/f/18103887-517943080-e03449
(访问密码:2604)
驱动下载后放到指定目录入:D://selenium//

创建maven project
引入pom配置文件:

org.seleniumhq.selenium selenium-java 3.4.0

定义java类,启动浏览器驱动:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeUtils {

public static WebDriver getDriver() {
	//设置浏览器驱动
	System.setProperty("webdriver.chrome.driver", "D:/selenium/chromedriver.exe");
	return new ChromeDriver(); // Chrome浏览器
}

public static void main(String[] args) {
	getDriver();
}

}

所有的代码:
package com.gp.www.zhuaqu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.gp.www.util.ChromeUtils;
import com.gp.www.util.DateTimeUtils;
import com.gp.www.util.FileUtils;
import com.gp.www.util.ThreadUtils;

/**

  • 循环遍历股票代码,获取所有股票的基本信息
  • @author wuyb

*/
public class GetGuPiaoInfo {

private WebDriver driver = null;

private BufferedReader bufferedReader;

private int count=0; //记录处理的个数

private int top =30;//当前焦点与上边距的距离

private void getInfo() {
	driver = ChromeUtils.getDriver(); // Chrome浏览器
	driver.get("http://quote.eastmoney.com/center/gridlist.html#hs_a_board");

	// 获取总页数 根据页面的样式 获取股票列表的总页数
	WebElement span = driver.findElement(By.cssSelector(".paginate_page"));
	List<WebElement> hrefs = span.findElements(By.tagName("a"));
	WebElement a = hrefs.get(hrefs.size() - 1);
	String totalPageStr = a.getText();
	System.out.println(totalPageStr);
	int totalPage = Integer.parseInt(totalPageStr);

	//按总页数循环遍历
	for (int i = 0; i < totalPage; i++) {
		
		//1股票信息以table表格的形式展示 先获取table信息
		WebElement table = driver.findElement(By.id("table_wrapper-table"));
		System.out.println("table:" + table);

		//2获取每一行的信息
		List<WebElement> trs = table.findElements(By.tagName("tr"));
		System.out.println("trs:" + trs.size());

		// 逐个股票处理 按行处理
		trs.stream().forEach(x -> anlizeTr(x));

		// 模拟点击下一页处理
		WebElement next = driver.findElement(By.cssSelector(".next"));
		next.click();

		System.out.println("点击下一页" + (i + 2));

		ThreadUtils.sleep(3000);
		count=0;
		scrollBy();
		((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", table);  
	}
	
	try {
		bufferedReader.close();
		FileUtils.closeFileWrite();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

//处理页面中一行的记录
public void anlizeTr(WebElement x) {
	//获取tr中的所有td
	List<WebElement> tds = x.findElements(By.tagName("td"));
	String code = null;
	if (!tds.isEmpty()) {
		//第二列为股票代码列 可以点击进入股票详细信息页面(子页面)
		code = tds.get(1).getText();
		System.out.println("code:" + tds.get(1).getText() + " name:" + tds.get(2).getText());
		tds.get(2).click();// 弹出单个股票的页面  模拟点击链接
		ThreadUtils.sleep(1000);
		
		//弹出新页面后,需要定位到新弹出的页面 使用如下方法定位到新弹出的页面
		String current = driver.getWindowHandle();//当前使用的页面句柄
		Set<String> handles = driver.getWindowHandles(); //所有打开的页面
		Iterator<String> it = handles.iterator();
		//循环遍历 切换页面句柄
		while (it.hasNext()) {
			String handle = it.next();
			if (!handle.equals(current)) {
				driver = driver.switchTo().window(handle); // 切换到新的句柄所指向的窗口
				break;
			}
		}

		//获取新页面的股票信息
		WebElement table = driver.findElement(By.cssSelector(".yfw"));
		System.out.println("新页面table:" + table);

		ThreadUtils.sleep(800);

		// 获取tr
		List<WebElement> trs = table.findElements(By.tagName("tr"));
		System.out.println("tr的数量:" + trs.size());

		//抓取股票的基本信息
		String text = trs.stream().map(tr -> tr.getText()).collect(Collectors.joining(" "));
		text = DateTimeUtils.getToday() + " " + text;
		System.out.println("基本信息:" + text);

		//将股票信息写入文件
		String path = "G://股票//股票基本信息" + code + ".txt";
		try {
			if(!findStringInFile(path,DateTimeUtils.getToday())) {
				FileUtils.writeToFile(text, path);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		//关闭新窗口(子页面) 并将句柄转移到父页面
		System.out.println("关闭窗口");
		driver.close();
		driver = driver.switchTo().window(current);
		count++;
		ThreadUtils.sleep(800);
		scrollBy();
	}
}

/**
 * 验证文件中是否包含字符串
 * 如果已经有今天的股票信息 则跳过不写入文件
 * @param path
 * @param day
 * @return
 * @throws IOException
 */
public  boolean findStringInFile(String path, String day) throws IOException {
	File file = new File(path);
	if(!file.exists()) {
		return false;
	}
	InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");// 考虑到编码格式
	bufferedReader = new BufferedReader(read);
	String line = null;
	while ((line = bufferedReader.readLine()) != null) {
		// 指定字符串判断处
		if (line.contains(day)) {
			return true;
		}
	}
	return false;
}

/**
 * 页面上线滑动
 * 当不能获取页面元素时 需要调整这个方法里的参数
 */
private void scrollBy() {
	((JavascriptExecutor) driver).executeScript("window.scrollBy(0, "+(top)+")");
	if(top==0) {
		//页面置顶
		((JavascriptExecutor) driver).executeScript("window.scrollTo(0, 10)");
		
		System.out.println("1111top:顶部");
	}
	System.out.println("1111top:"+(count*top));
}

public void anlizerTd(WebElement tr) {
	System.out.println(tr.getText());
}

public static void main(String[] args) {
	GetGuPiaoInfo gg = new GetGuPiaoInfo();
	gg.getInfo();
}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值