博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用selenium动态爬取
阅读量:4202 次
发布时间:2019-05-26

本文共 2300 字,大约阅读时间需要 7 分钟。

支持动态爬取,如登录、Javascript内容。

一、准备:

1、下载selenium(如:selenium-java-2.37.0.zip,约24MB),chromedriver.exe(chromedriver_win32.zip,约2.4MB)

https://sites.google.com/a/chromium.org/chromedriver/downloads

2、设置driver,参考:

http://download.csdn.net/detail/qianaier/7966945

二、开发:

连接例子

System.setProperty("webdriver.chrome.driver", 				"C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");		WebDriver driver = new ChromeDriver();

登录例子

driver.get("https://xx.xxx.xx/admin/login.jsp");		driver.findElement(By.id("input_username")).clear();		driver.findElement(By.id("input_username")).sendKeys("username");		driver.findElement(By.id("input_password")).clear();		driver.findElement(By.id("input_password")).sendKeys("password");		// log on		driver.findElement(By.className("btn")).click();		System.out.println(driver.getTitle());
子元素访问例子(By.id/className/tagName)
WebElement sub = driver.findElement(By.id("accordion-element"));		List
subList = sub.findElement(By.className("accordion-inner")). findElement(By.className("nav-list")).findElements(By.tagName("li")); for (WebElement li:subList) { WebElement href = li.findElement(By.tagName("a"));
属性、文本内容

if (div1.getAttribute("style").contains("margin-bottom: 10px;")) {								// detail								System.out.println(div1.findElement(By.tagName("div")).getText());
内部页面跳转

WebDriver frameDriver = driver.switchTo().frame("iframe_1");

隐藏元素

-- 不能获取的例子

if (closeButton.getText().equals("关闭")) {				closeButton.click();			}

-- 可以获取的例子

if (closeButton.getAttribute("innerText").equals("关闭")) {				((JavascriptExecutor) frameDriver).executeScript(""						+ "document.getElementsByClassName('modal')[0]."						+ "getElementsByClassName('btn')[0].click()");			}

机器操作太快引起元素找不到

// 加上sleep				try {					Thread.sleep(500);				} catch (InterruptedException e) {					e.printStackTrace();				}				closeButton.click();

退出

frameDriver.quit();driver.quit();

Reference

Selenium定位不到元素的解决方法—iframe挡住了去路  http://www.51testing.com/html/02/n-855802.html

selenium webdriver 学习总结-浏览器启动方式  http://blog.csdn.net/pugongying1988/article/details/14525013

使用Selenium来抓取动态加载的页面  http://my.oschina.net/flashsword/blog/147334

Selenium Test 自动化测试 入门级学习笔记  http://www.renren.com

隐藏元素 http://my.oschina.net/longtutengfei/blog/166773,http://www.open-open.com/lib/view/open1402750704931.html

你可能感兴趣的文章
list.forEach 用法
查看>>
Java 读取本地 Excel 文件
查看>>
通用 Mapper4 使用
查看>>
Vue 代码练习
查看>>
baomidou 动态数据源
查看>>
fastjson 用法记录
查看>>
java.util.stream.Stream#map
查看>>
Elastic Job Lite v2.1.6控制台
查看>>
ES DSL语句
查看>>
go eclipse 环境搭建
查看>>
Prometheus 安装
查看>>
Error running ‘Application‘: command line is too long
查看>>
VSCode搭建Go开发环境
查看>>
安装 Helm
查看>>
CentOS Docker 安装
查看>>
VictoriaMetrics 学习
查看>>
Java Double 避免科学计数法
查看>>
搭建 Spring MVC 项目用到的 JAR 包
查看>>
idea 错误: 找不到或无法加载主类
查看>>
Spring Boot访问不到controller
查看>>