不同网站有不同特性,需要掌握selenim基本网页元素定位以及浏览器控制,本文解析网页主要实现以下操作:

1)模拟鼠标操作,点击按钮提交;2)获取浏览器窗口句柄,切换到当前窗口下操作;3)处理不带总页数的列表页,设计两个变量iDyn和iSta并定位下一页来翻译;4)处理弹出框alert;5)通过对元素定位支持不同网页模板的信息采集,元素下再采集子元素;6)网页内table元素的处理。具体代码如下:

package com.test;import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;import com.util.Logs;public class Shop114YP {public static void main(String[] args) {System.getProperties().setProperty("webdriver.chrome.driver","D:\\dev\\workspace\\ocweb\\libs\\chromedriver.exe"); WebDriver webDriver = new ChromeDriver();WebDriver wd = new ChromeDriver();int iCount=0;//统计输出多少try {webDriver.get("url");//访问网址//等待页面加载完毕,直到条件满足  (new WebDriverWait(webDriver, 30)).until(new ExpectedCondition<Boolean>() {  public Boolean apply(WebDriver dr) {  int index = dr.getPageSource().indexOf("keyword");  if(index != -1){                            return true;  //找到,退出等待}else{  return false;  //未找到,继续等待}  }  });//通过 id 找到 input的 DOMActions action=new Actions(webDriver); //模拟鼠标操作WebElement eleKeyword = webDriver.findElement(By.name("keyword"));action.sendKeys(eleKeyword,"内容").perform();//获取窗口当前句柄Set<String> bHandlers = webDriver.getWindowHandles();String bHandler = bHandlers.iterator().next();//执行点击操作,打开一个新的页面WebElement eleSearch = webDriver.findElement(By.className("search_shu4")); action.moveToElement(eleSearch);  action.click().perform(); //打开一个新页面//获取窗口当前句柄Set<String> nHandlers = webDriver.getWindowHandles();nHandlers.remove(bHandler);//移除先前页面String nHandler = nHandlers.iterator().next();//获取最新打开的句柄webDriver.switchTo().window(nHandler);//切换到新打开的页面//webDriver.switchTo().window(bHandler);//返回原页面(new WebDriverWait(webDriver, 30)).until(new ExpectedCondition<Boolean>() {  public Boolean apply(WebDriver dr) {  int index = dr.getPageSource().indexOf("内容");  if(index != -1) return true;  //找到,退出等待else return false;  //未找到,继续等待              }  });//进入搜索结果页面,第一页int iDyn=1;int iSta=1;      while(iSta==iDyn){List<WebElement> comList =webDriver.findElements(By.partialLinkText("内容"));for(WebElement ele:comList){//处理每一项iCount++;String com=ele.getText();//公司名String link=ele.getAttribute("href"); //if(!link.contains("shopid")) continue;//不包含shopid的链接不要wd.get(link);            try{Alert alert = wd.switchTo().alert();//判断是否有js弹出框if (null == alert){//没弹出throw new NoAlertPresentException();}else {alert.accept();continue;}}catch (NoAlertPresentException e) {//System.out.println("There is no alert appear!");}    //支持不同网页模板的信息采集if(wd.getPageSource().contains("lianxi-text")){//打开页面List<WebElement> contactList =wd.findElements(By.id("lianxi-text"));for(WebElement eleCon:contactList){String txt=eleCon.getText();com=com+"|"+txt;}           }else if(wd.getPageSource().contains("tablebg")){//网页table处理WebElement table = wd.findElement(By.className("tablebg")); //获取table元素List<WebElement> rows = table.findElements(By.tagName("tr"));//获取table内行元素//List<WebElement> cells=rows.get(0).findElements(By.tagName("td"));//获取row第一行中的所有列for(WebElement row:rows) com=com+"|"+row.getText();}else if(wd.getPageSource().contains("table2")){List<WebElement> cells = wd.findElements(By.tagName("td"));//获取td元素for(WebElement cell:cells){if(cell.getAttribute("class").equals("table2") || cell.getAttribute("class").equals("table") ){com=com+"|"+cell.getText();}}}else if(wd.getPageSource().contains("sidenei")){WebElement elesn=wd.findElement(By.className("sidenei"));List<WebElement> eleNeis = elesn.findElements(By.className("nei"));//class等于nei的元素for(WebElement elenei:eleNeis) com=com+"|"+elenei.getText();}else if(wd.getPageSource().contains("liebiao")){WebElement eleLibiao=wd.findElement(By.className("liebiao"));List<WebElement> eleLbs = eleLibiao.findElements(By.id("li"));//ul下li元素for(WebElement eleLb:eleLbs) com=com+"|"+eleLb.getText();}Logs.writeLogs(com);                              }//进入下一页,找到下一页链接iDyn++;WebElement pageEle =webDriver.findElement(By.linkText("下一页"));String pagelink=pageEle.getAttribute("href");Pattern ps= Pattern.compile("[?&=]+");String[] values=ps.split(pagelink);iSta=Integer.valueOf(values[values.length-1]);webDriver.get(pagelink);(new WebDriverWait(webDriver, 30)).until(new ExpectedCondition<Boolean>() {  public Boolean apply(WebDriver dr) {  int index = dr.getPageSource().indexOf("内容"); if(index != -1) return true;  //找到,退出等待else return false;  //未找到,继续等待              }  });        }       }catch (Exception e) { System.err.println( "Exception: " + e );}System.out.println(iCount);wd.close();wd.quit();webDriver.close();webDriver.quit();}
}

模拟浏览器自动化测试工具Selenium之三页面窗口切换开发篇相关推荐

  1. 模拟浏览器自动化测试工具Selenium之二Html基本元素开发篇

    发现用IE浏览器,有很多动态网站加载错误,只好安装chrome浏览器,然后下载chrome driver来驱动.通过selenium的基本元素定位操作来和网页交互. 网页解析主要动作:1)表单自动填写 ...

  2. 模拟浏览器自动化测试工具Selenium之四cssSelector元素定位开发篇

    Selenium官网的Document里推荐使用CSS locator,而不是XPath来定位元素,原因是CSS locator比XPath locator速度快,特别是在IE下面(IE没有自己的XP ...

  3. 模拟浏览器自动化测试工具Selenium之一eclipse集成开发部署篇

    1.背景:在网页自动化测试和网页表单自动交互的场景中,对动态js页面的加载,隐藏链接爬虫和表单元素需要加载js来解析. htmlunit相比较于htmlparser以及httpclient只能解析静态 ...

  4. 模拟浏览器自动化测试工具Selenium之五Centos系统命令行下部署selenium环境试验

    一.背景:     Selenium是一个web自动化测试框架,也支持从HTML页面上爬取javascript生成的或AJAX的内容.     selenium2支持通过各种driver(Firfox ...

  5. 模拟浏览器自动化测试工具Selenium之七采集网页信息写入excel

    功能:从网页上采集信息写入excel,有鼠标移动到相关元素代码,参考如下: package com.test;import java.io.DataInputStream; import java.i ...

  6. 模拟浏览器自动化测试工具Selenium之六设置代理篇

    在使用Selenium自动化测试时,如果需要设置代理访问网络时,可以参考如下代码: package com.test;import java.util.List; import org.openqa. ...

  7. Python学习笔记(一)——浏览器自动化测试工具Selenium

    看了网友用Python通过影评来分析电影是好片还是烂片,自己也有了个想法想去分析下百度贴吧的帖子是精品帖子还是水帖子.目前正在熟悉工具的使用. 会用到的库:Selenium, pandas(数据模型) ...

  8. Selenium浏览器自动化测试工具

    目录 Selenium浏览器自动化测试工具 Selenium模块在爬虫中的使用 Python简单使用Selenium Selenium的基本操作 Selenium爬取动态加载的数据 Selenium动 ...

  9. 使用selenium模拟浏览器,获取淘宝搜索页面商品名称销量等信息

    作者:李忠林 Github: https://github.com/Leezhonglin Gitblog: https://leezhonglin.github.io/ 本文仅用于学习. 使用自动化 ...

最新文章

  1. PHP Notice: undefined index xxx
  2. Java使用S3的一些操作
  3. Java使用lowagie根据模版动态生成PDF(无需额外设置系统字体)
  4. 面试分享|机械行业面试常见问题有哪些
  5. 南京大学计算机视觉博士生导师,孙正兴——著名计算机专家孙正兴——南京大学教授...
  6. 还在用网盘备份同步3D图纸?你落伍了
  7. Charles手机的代理配置与证书的安装
  8. 这世界无非是“人人为我,我为人人”
  9. thingsboard 规则引擎结点功能总结
  10. 2022计算机保研心得
  11. java程序是怎么执行的
  12. 微机原理与接口技术复习笔记(1)——微型计算机概述
  13. Java程序设计基础【10】
  14. 交流电源和直流电源有什么区别?
  15. 英语读书笔记-Book Lovers Day 04
  16. 腾讯会议突围背后:端到端实时语音技术是如何保障交流通畅的?
  17. 我们分析了400位华语歌手的歌词,发现人们重点关注的人事物情
  18. 计算机桌面垃圾筒怎么恢复出来,桌面垃圾桶被误删了,怎么恢复
  19. 考研复试英语介绍计算机专业,2018计算机考研复试英语自我介绍范本及重点
  20. BERT原理和结构详解

热门文章

  1. linux apache守护进程,Linux基础命令---httpd守护进程
  2. python链表添加多个值_Python基础10之数据结构(下)
  3. 区块链 java 开源_详细介绍Java区块链开源代码背后的内容
  4. web浏览器_你最常用的web测试-浏览器兼容性测试
  5. XML数据读取方式性能比较(一)
  6. 使用.reg文件删除暴风影视库图标和注册信息
  7. Android Studio项目结构
  8. 【Android-功能】Android应用增量更新
  9. ZOJ Problem Set - 3329 One Person Game
  10. 金山词霸2012不能在PDF中取词 解决办法