当前位置:   article > 正文

java调用seleniumjs爬取动态网站信息_gate in empty

gate in empty
以前自己对网站数据爬取进行过一段时间的研究,接下来分享一下我的数据爬虫之路。

数据爬取的对象主要分为两种:

    静态数据:静态数据很好爬取,直接通过httpClient等框架就能爬取,因为请求后会直接将数据结果返回给你。

    动态数据:动态数据则需要将网络数据加载到浏览器端,通过一定的javascript脚本运行后,才能输出我们想要的第一步结果,为什么说第一步结果,因为在数据爬虫中,我们想要的数据往往不是来源于一个页面,通常都是通过主页面,点击某个按钮后获取到一个信息列表,然后在这个信息列表中点击某个信息详情才能获取到这个信息的详细数据,而数据爬取往往都是先获取到主页,然后通过某些关键字或者主页上的某些按钮进行数据自动爬取,那么我们接下来说说如何通过Java实现网页数据自动爬取。

    原来我使用过一些其他的爬虫框架,比如Jsoup,htmlunit等,这个框架对于一些简单的网站爬取没有任何问题,但是对于比较复杂的网站爬取就存在数据获取不到的问题了,比如动态页面Jsoup就不支持了,而对于存在内部跳转的网页htmlunit就获取不到信息了,在后来的研究中,我找到了selenium这个框架,一开始为了测试我是用的是selenium webdriver,这个就是基于浏览器浏览器去获取数据,每调用一次就会打开一个浏览器窗口去加载你的请求地址。


代码区域

使用到的框架如下:

<dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>phantomjsdriver</artifactId>
            <version>1.2.1</version>
        </dependency>

需要手动下载相对于的应用应用程序,由于我的系统是macOS所以我下载的是phantomjs-2.1.1-macosx,下载地址为:phantomjs下载地址,根据不同系统下载不同版本。

我们要爬取的网站为:www.hapag-lloyd.cn 这个是物流信息网站,接下来我们来爬取这个物流信息。

网站展示界面如下:


操作流程:

我们觉得应该通过程序自动输入集装箱号,然后自动点击查询按钮,提交订单查询请求,如下图:


首先分析页面html代码,我们要做的事情就是通过代码将文本框的集装箱号码自动填上,然后自动触发跟踪按钮的点击事件,好比网页的自动化测试,首先分析html结构,结构如下如:


核心代码如下:

try{

            WebElement inputElement = driver.findElement(By.id("tracing_by_booking_f:hl21"));
            WebElement tableElement = inputElement.findElement(By.id("tracing_by_booking_f:hl27"));
                    WebElement tbodyElement = tableElement.findElement(By.tagName("tbody"));
                    List<WebElement> listElement = tbodyElement.findElements(By.tagName("tr"));
                    JSONArray arrayJson = new JSONArray();
                    for (WebElement trElement : listElement) {
                        WebElement radioElement = trElement.findElement(By.tagName("input"));
                        List<WebElement> tdElements = trElement.findElements(By.tagName("td"));
                        JSONObject infoJsonObject = new JSONObject();
                        arrayJson.add(infoJsonObject);
                        infoJsonObject.put("箱型", tdElements.get(1).getText());
                        infoJsonObject.put("箱号", tdElements.get(2).getText());
                        infoJsonObject.put("操作状态", tdElements.get(3).getText());
                        infoJsonObject.put("操作日期", tdElements.get(4).getText());
                        infoJsonObject.put("操作地点", tdElements.get(5).getText());
                        String snNumber = tdElements.get(2).getText();
                        String[] nums = snNumber.split("\\s+");
                        // String type = radioElement.getAttribute("type");
                        String url = null;
                        if (nums.length > 1) {
                            url = "https://www.hapag-lloyd.cn/zh/online-business/tracing/tracing-by-booking.html?view=S8510&container=" + nums[0] + "++" + nums[1];
                        } else {
                            url = "https://www.hapag-lloyd.cn/zh/online-business/tracing/tracing-by-booking.html?view=S8510";
                        }
                        PhantomJSDriver newDriver = getDriver();
                        newDriver.get(url);
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        JSONObject newinfoobject = new JSONObject();
                        infoJsonObject.put("detail", newinfoobject);
                        System.out.println(newDriver.getPageSource());
                        loadsuccess = false;
                        while(!loadsuccess){
                            if(initOk(newDriver,checkTimes,By.id("tracing_by_booking_f:hl29"))){
                                loadsuccess = true;
                            }
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        WebElement newinfoTableElement = newDriver.findElement(By.id("tracing_by_booking_f:hl29"));
                        WebElement newinfotrElmenet = newinfoTableElement.findElement(By.className("boxContent")).findElement(By.tagName("tr"));
                        List<WebElement> newinfotdsElmenet = newinfotrElmenet.findElements(By.xpath("td[contains(@style,'white-space:nowrap;')]"));
                        System.out.println(newinfoTableElement.getText());
                        newinfoobject.put("箱型", newinfotdsElmenet.get(0).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("描述", newinfotdsElmenet.get(1).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("尺寸", newinfotdsElmenet.get(2).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("Tare(kg)", newinfotdsElmenet.get(3).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("Max.Payload(kg)", newinfotdsElmenet.get(4).findElements(By.tagName("td")).get(1).getText());
                        WebElement newltableElement = newDriver.findElement(By.id("tracing_by_booking_f:hl62"));
                        WebElement newTableElement = newltableElement.findElement(By.id("tracing_by_booking_f:hl66"));
                        WebElement newtbodyElement = newTableElement.findElement(By.tagName("tbody"));
                        List<WebElement> newtrsElement = newtbodyElement.findElements(By.tagName("tr"));
                        //JsonArray
                        JSONArray newtrarray = new JSONArray();
                        infoJsonObject.put("infolist", newtrarray);
                        for (WebElement newtrElement : newtrsElement) {
                            List<WebElement> newtdsElement = newtrElement.findElements(By.tagName("td"));
                            JSONObject newtdjson = new JSONObject();
                            newtdjson.put("operate", newtdsElement.get(0).getText());
                            newtdjson.put("operateaddress", newtdsElement.get(1).getText());
                            newtdjson.put("date", newtdsElement.get(2).getText());
                            newtdjson.put("time", newtdsElement.get(3).getText());
                            newtdjson.put("transport", newtdsElement.get(4).getText());
                            newtdjson.put("hc", newtdsElement.get(5).getText());
                            newtrarray.add(newtdjson);
                        }
                        Object[] strList = newDriver.getWindowHandles().toArray();

                        newDriver.close();
                        newDriver.quit();
                    }
                    jedis.sadd("so:hlc:"+bkNo+":reslut",arrayJson.toString());
                    System.out.println(arrayJson.toString());

        }catch(Exception e){
            e.printStackTrace();
        }

数据爬取结果如下:

  1. [
  2. {
  3. "操作状态": "Gate in empty",
  4. "操作日期": "2018-02-15",
  5. "箱型": "45GP",
  6. "箱号": "TRLU 7359129",
  7. "infolist": [
  8. {
  9. "date": "2018-04-26",
  10. "operate": "Gate out empty",
  11. "time": "03:57",
  12. "transport": "Truck",
  13. "hc": "",
  14. "operateaddress": "NINGBO"
  15. },
  16. {
  17. "date": "2018-04-26",
  18. "operate": "Arrival in",
  19. "time": "13:42",
  20. "transport": "Truck",
  21. "hc": "",
  22. "operateaddress": "NINGBO"
  23. },
  24. {
  25. "date": "2018-05-04",
  26. "operate": "Loaded",
  27. "time": "06:29",
  28. "transport": "LINAH",
  29. "hc": "005W",
  30. "operateaddress": "NINGBO"
  31. },
  32. {
  33. "date": "2018-05-04",
  34. "operate": "Vessel departed",
  35. "time": "07:00",
  36. "transport": "LINAH",
  37. "hc": "005W",
  38. "operateaddress": "NINGBO"
  39. },
  40. {
  41. "date": "2018-06-04",
  42. "operate": "Vessel arrived",
  43. "time": "10:48",
  44. "transport": "LINAH",
  45. "hc": "005W",
  46. "operateaddress": "HAMBURG"
  47. },
  48. {
  49. "date": "2018-06-05",
  50. "operate": "Discharged",
  51. "time": "11:21",
  52. "transport": "LINAH",
  53. "hc": "005W",
  54. "operateaddress": "HAMBURG"
  55. }
  56. ],
  57. "detail": {
  58. "箱型": "45GP",
  59. "尺寸": "40' X 8' X 9'6\"",
  60. "Max.Payload(kg)": "28620",
  61. "描述": "HIGH CUBE CONT.",
  62. "Tare(kg)": "3880"
  63. },
  64. "操作地点": "SAVANNAH, GA"
  65. },
  66. {
  67. "操作状态": "Gate in empty",
  68. "操作日期": "2018-02-15",
  69. "箱型": "45GP",
  70. "箱号": "HLXU 8065397",
  71. "infolist": [
  72. {
  73. "date": "2018-04-06",
  74. "operate": "Gate out empty",
  75. "time": "19:11",
  76. "transport": "Truck",
  77. "hc": "",
  78. "operateaddress": "QINGDAO"
  79. },
  80. {
  81. "date": "2018-04-07",
  82. "operate": "Arrival in",
  83. "time": "21:52",
  84. "transport": "Truck",
  85. "hc": "",
  86. "operateaddress": "QINGDAO"
  87. },
  88. {
  89. "date": "2018-04-12",
  90. "operate": "Loaded",
  91. "time": "19:45",
  92. "transport": "ALEXANDRA",
  93. "hc": "817E",
  94. "operateaddress": "QINGDAO"
  95. },
  96. {
  97. "date": "2018-04-13",
  98. "operate": "Vessel departed",
  99. "time": "00:45",
  100. "transport": "ALEXANDRA",
  101. "hc": "817E",
  102. "operateaddress": "QINGDAO"
  103. },
  104. {
  105. "date": "2018-04-15",
  106. "operate": "Vessel arrived",
  107. "time": "11:30",
  108. "transport": "ALEXANDRA",
  109. "hc": "817E",
  110. "operateaddress": "BUSAN"
  111. },
  112. {
  113. "date": "2018-04-15",
  114. "operate": "Discharged",
  115. "time": "15:03",
  116. "transport": "ALEXANDRA",
  117. "hc": "817E",
  118. "operateaddress": "BUSAN"
  119. },
  120. {
  121. "date": "2018-04-29",
  122. "operate": "Loaded",
  123. "time": "20:00",
  124. "transport": "COPIAPO",
  125. "hc": "816E",
  126. "operateaddress": "BUSAN"
  127. },
  128. {
  129. "date": "2018-04-30",
  130. "operate": "Vessel departed",
  131. "time": "12:24",
  132. "transport": "COPIAPO",
  133. "hc": "816E",
  134. "operateaddress": "BUSAN"
  135. },
  136. {
  137. "date": "2018-05-27",
  138. "operate": "Vessel arrived",
  139. "time": "15:39",
  140. "transport": "COPIAPO",
  141. "hc": "816E",
  142. "operateaddress": "IQUIQUE"
  143. },
  144. {
  145. "date": "2018-05-27",
  146. "operate": "Discharged",
  147. "time": "17:21",
  148. "transport": "COPIAPO",
  149. "hc": "816E",
  150. "operateaddress": "IQUIQUE"
  151. },
  152. {
  153. "date": "2018-05-31",
  154. "operate": "Departure from",
  155. "time": "08:43",
  156. "transport": "Truck",
  157. "hc": "",
  158. "operateaddress": "IQUIQUE"
  159. },
  160. {
  161. "date": "2018-05-31",
  162. "operate": "Gate in empty",
  163. "time": "10:15",
  164. "transport": "Truck",
  165. "hc": "",
  166. "operateaddress": "IQUIQUE"
  167. }
  168. ],
  169. "detail": {
  170. "箱型": "45GP",
  171. "尺寸": "40' X 8' X 9'6\"",
  172. "Max.Payload(kg)": "28550",
  173. "描述": "HIGH CUBE CONT.",
  174. "Tare(kg)": "3950"
  175. },
  176. "操作地点": "SAVANNAH, GA"
  177. },
  178. {
  179. "操作状态": "Gate in empty",
  180. "操作日期": "2018-02-15",
  181. "箱型": "45GP",
  182. "箱号": "CPSU 6435050",
  183. "infolist": [
  184. {
  185. "date": "2018-03-21",
  186. "operate": "Arrival in",
  187. "time": "13:02",
  188. "transport": "Truck",
  189. "hc": "",
  190. "operateaddress": "BELFAST, NORTHERN IRELAND"
  191. },
  192. {
  193. "date": "2018-03-23",
  194. "operate": "Loaded",
  195. "time": "23:35",
  196. "transport": "PHOENIX J",
  197. "hc": "181243",
  198. "operateaddress": "BELFAST, NORTHERN IRELAND"
  199. },
  200. {
  201. "date": "2018-03-24",
  202. "operate": "Vessel departed",
  203. "time": "00:01",
  204. "transport": "PHOENIX J",
  205. "hc": "181243",
  206. "operateaddress": "BELFAST, NORTHERN IRELAND"
  207. },
  208. {
  209. "date": "2018-03-24",
  210. "operate": "Vessel arrived",
  211. "time": "07:00",
  212. "transport": "PHOENIX J",
  213. "hc": "181243",
  214. "operateaddress": "LIVERPOOL"
  215. },
  216. {
  217. "date": "2018-03-24",
  218. "operate": "Discharged",
  219. "time": "17:29",
  220. "transport": "PHOENIX J",
  221. "hc": "181243",
  222. "operateaddress": "LIVERPOOL"
  223. },
  224. {
  225. "date": "2018-03-31",
  226. "operate": "Loaded",
  227. "time": "11:36",
  228. "transport": "MSC ALYSSA",
  229. "hc": "127W12",
  230. "operateaddress": "LIVERPOOL"
  231. },
  232. {
  233. "date": "2018-03-31",
  234. "operate": "Vessel departed",
  235. "time": "23:30",
  236. "transport": "MSC ALYSSA",
  237. "hc": "127W12",
  238. "operateaddress": "LIVERPOOL"
  239. },
  240. {
  241. "date": "2018-04-08",
  242. "operate": "Vessel arrived",
  243. "time": "10:54",
  244. "transport": "MSC ALYSSA",
  245. "hc": "127W12",
  246. "operateaddress": "MONTREAL, QC"
  247. },
  248. {
  249. "date": "2018-04-10",
  250. "operate": "Discharged",
  251. "time": "05:17",
  252. "transport": "MSC ALYSSA",
  253. "hc": "127W12",
  254. "operateaddress": "MONTREAL, QC"
  255. },
  256. {
  257. "date": "2018-04-11",
  258. "operate": "Departure from",
  259. "time": "06:11",
  260. "transport": "Rail",
  261. "hc": "",
  262. "operateaddress": "MONTREAL, QC"
  263. },
  264. {
  265. "date": "2018-04-13",
  266. "operate": "Arrival in",
  267. "time": "20:10",
  268. "transport": "Rail",
  269. "hc": "",
  270. "operateaddress": "CHICAGO, IL"
  271. }
  272. ],
  273. "detail": {
  274. "箱型": "45GP",
  275. "尺寸": "40' X 8' X 9'6\"",
  276. "Max.Payload(kg)": "28560",
  277. "描述": "HIGH CUBE CONT.",
  278. "Tare(kg)": "3940"
  279. },
  280. "操作地点": "SAVANNAH, GA"
  281. },
  282. {
  283. "操作状态": "Gate in empty",
  284. "操作日期": "2018-02-15",
  285. "箱型": "45GP",
  286. "箱号": "GLDU 7588155",
  287. "infolist": [
  288. {
  289. "date": "2018-04-21",
  290. "operate": "Gate out empty",
  291. "time": "16:14",
  292. "transport": "Truck",
  293. "hc": "",
  294. "operateaddress": "QINGDAO"
  295. },
  296. {
  297. "date": "2018-04-23",
  298. "operate": "Arrival in",
  299. "time": "10:37",
  300. "transport": "Truck",
  301. "hc": "",
  302. "operateaddress": "QINGDAO"
  303. },
  304. {
  305. "date": "2018-05-02",
  306. "operate": "Loaded",
  307. "time": "22:38",
  308. "transport": "MANHATTAN BRIDGE",
  309. "hc": "014W",
  310. "operateaddress": "QINGDAO"
  311. },
  312. {
  313. "date": "2018-05-03",
  314. "operate": "Vessel departed",
  315. "time": "01:30",
  316. "transport": "MANHATTAN BRIDGE",
  317. "hc": "014W",
  318. "operateaddress": "QINGDAO"
  319. },
  320. {
  321. "date": "2018-06-02",
  322. "operate": "Vessel arrived",
  323. "time": "22:24",
  324. "transport": "MANHATTAN BRIDGE",
  325. "hc": "014W",
  326. "operateaddress": "PIRAEUS"
  327. },
  328. {
  329. "date": "2018-06-03",
  330. "operate": "Discharged",
  331. "time": "08:52",
  332. "transport": "MANHATTAN BRIDGE",
  333. "hc": "014W",
  334. "operateaddress": "PIRAEUS"
  335. },
  336. {
  337. "date": "2018-06-05",
  338. "operate": "Loaded",
  339. "time": "06:01",
  340. "transport": "FRITZ REUTER",
  341. "hc": "1822N",
  342. "operateaddress": "PIRAEUS"
  343. },
  344. {
  345. "date": "2018-06-05",
  346. "operate": "Vessel departure",
  347. "time": "23:00",
  348. "transport": "FRITZ REUTER",
  349. "hc": "1822N",
  350. "operateaddress": "PIRAEUS"
  351. },
  352. {
  353. "date": "2018-06-13",
  354. "operate": "Vessel arrival",
  355. "time": "08:00",
  356. "transport": "FRITZ REUTER",
  357. "hc": "1822N",
  358. "operateaddress": "CONSTANTA"
  359. }
  360. ],
  361. "detail": {
  362. "箱型": "45GP",
  363. "尺寸": "40' X 8' X 9'6\"",
  364. "Max.Payload(kg)": "28720",
  365. "描述": "HIGH CUBE CONT.",
  366. "Tare(kg)": "3780"
  367. },
  368. "操作地点": "SAVANNAH, GA"
  369. },
  370. {
  371. "操作状态": "Gate in empty",
  372. "操作日期": "2018-02-16",
  373. "箱型": "45GP",
  374. "箱号": "HLXU 8105036",
  375. "infolist": [
  376. {
  377. "date": "2018-05-30",
  378. "operate": "Gate out empty",
  379. "time": "16:36",
  380. "transport": "Truck",
  381. "hc": "",
  382. "operateaddress": "MIAMI, FL"
  383. },
  384. {
  385. "date": "2018-06-04",
  386. "operate": "Arrival in",
  387. "time": "08:48",
  388. "transport": "Truck",
  389. "hc": "",
  390. "operateaddress": "PORT EVERGLADES, FL"
  391. },
  392. {
  393. "date": "2018-06-07",
  394. "operate": "Vessel departure",
  395. "time": "15:00",
  396. "transport": "LIMARI",
  397. "hc": "0170S",
  398. "operateaddress": "PORT EVERGLADES, FL"
  399. },
  400. {
  401. "date": "2018-06-21",
  402. "operate": "Vessel arrival",
  403. "time": "09:00",
  404. "transport": "LIMARI",
  405. "hc": "0170S",
  406. "operateaddress": "SAN ANTONIO"
  407. }
  408. ],
  409. "detail": {
  410. "箱型": "45GP",
  411. "尺寸": "40' X 8' X 9'6\"",
  412. "Max.Payload(kg)": "28550",
  413. "描述": "HIGH CUBE CONT.",
  414. "Tare(kg)": "3950"
  415. },
  416. "操作地点": "SAVANNAH, GA"
  417. }
  418. ]

总结:

该网页爬取一共爬取了三层网页,通过模拟页面按钮点击事件触发页面请求跳转。

   1.   2.   3.


以下为数据爬取全部代码:

HLCServiceThread.java

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

/**
 * Created by pengweikang on 2018/3/6.
 */
public class HLCServiceThread extends BaseService {




    private String indexUrl;
    private String bkNo;
    private int checkTimes = 10;


    public HLCServiceThread(String url ,int checkTimes){

        JSONObject json = UrlParamsUtils.getParams(url);

        this.indexUrl = json.getString("indexUrl");

        this.bkNo = json.getString("bkNo");
        this.checkTimes = checkTimes;
    }


    public HLCServiceThread(){}






    @Override
    public void run() {

        PhantomJSDriver driver = getDriver();
        Jedis jedis = RedisUtils.getJedis();
        driver.get("https://www.hapag-lloyd.cn/zh/home.html");

        /**
         * pengweikang 该代码主要解决网站存在内部跳转而导致网页数据爬取失败问题
         */
        boolean loadsuccess = false;
        while(!loadsuccess){
            if(initOk(driver,checkTimes,By.id("tracingvalue"))){
                loadsuccess = true;
            }
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        WebElement valueElement = driver.findElement(By.id("tracingvalue"));
        valueElement.sendKeys("80596513");
        WebElement buttonElement =  driver.findElements(By.className("hal-toggle-input-content")).get(0).findElement(By.tagName("button"));
        String text = buttonElement.getText();
        System.out.println(text);
        buttonElement.click();
        loadsuccess = false;
        while(!loadsuccess){
            if(initOk(driver,checkTimes,By.id("tracing_by_booking_f:hl21"))){
                loadsuccess = true;
            }
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try{

            WebElement inputElement = driver.findElement(By.id("tracing_by_booking_f:hl21"));
                    WebElement tableElement = inputElement.findElement(By.id("tracing_by_booking_f:hl27"))
                    WebElement tbodyElement = tableElement.findElement(By.tagName("tbody"));
                    List<WebElement> listElement = tbodyElement.findElements(By.tagName("tr"));
                    JSONArray arrayJson = new JSONArray();

                    for (WebElement trElement : listElement) {
                        WebElement radioElement = trElement.findElement(By.tagName("input"));
                        List<WebElement> tdElements = trElement.findElements(By.tagName("td"));
                        JSONObject infoJsonObject = new JSONObject();
                        arrayJson.add(infoJsonObject);
                        infoJsonObject.put("箱型", tdElements.get(1).getText());
                        infoJsonObject.put("箱号", tdElements.get(2).getText());
                        infoJsonObject.put("操作状态", tdElements.get(3).getText());
                        infoJsonObject.put("操作日期", tdElements.get(4).getText());
                        infoJsonObject.put("操作地点", tdElements.get(5).getText());
                        String snNumber = tdElements.get(2).getText();
                        String[] nums = snNumber.split("\\s+");
                        // String type = radioElement.getAttribute("type");
                        String url = null;
                        if (nums.length > 1) {
                            url = "https://www.hapag-lloyd.cn/zh/online-business/tracing/tracing-by-booking.html?view=S8510&container=" + nums[0] + "++" + nums[1];
                        } else {
                            url = "https://www.hapag-lloyd.cn/zh/online-business/tracing/tracing-by-booking.html?view=S8510";
                        }

                        PhantomJSDriver newDriver = getDriver();

                        newDriver.get(url);

                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //InfoJson
                        JSONObject newinfoobject = new JSONObject();
                        infoJsonObject.put("detail", newinfoobject);
                        System.out.println(newDriver.getPageSource());
                        loadsuccess = false;
                        while(!loadsuccess){
                            if(initOk(newDriver,checkTimes,By.id("tracing_by_booking_f:hl29"))){
                                loadsuccess = true;
                            }
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        WebElement newinfoTableElement = newDriver.findElement(By.id("tracing_by_booking_f:hl29"));
                        WebElement newinfotrElmenet = newinfoTableElement.findElement(By.className("boxContent")).findElement(By.tagName("tr"));
                        List<WebElement> newinfotdsElmenet = newinfotrElmenet.findElements(By.xpath("td[contains(@style,'white-space:nowrap;')]"));
                        System.out.println(newinfoTableElement.getText());
                        newinfoobject.put("箱型", newinfotdsElmenet.get(0).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("描述", newinfotdsElmenet.get(1).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("尺寸", newinfotdsElmenet.get(2).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("Tare(kg)", newinfotdsElmenet.get(3).findElements(By.tagName("td")).get(1).getText());
                        newinfoobject.put("Max.Payload(kg)", newinfotdsElmenet.get(4).findElements(By.tagName("td")).get(1).getText());
                        WebElement newltableElement = newDriver.findElement(By.id("tracing_by_booking_f:hl62"));
                        WebElement newTableElement = newltableElement.findElement(By.id("tracing_by_booking_f:hl66"));
                        WebElement newtbodyElement = newTableElement.findElement(By.tagName("tbody"));
                        List<WebElement> newtrsElement = newtbodyElement.findElements(By.tagName("tr"));
                        //JsonArray
                        JSONArray newtrarray = new JSONArray();

                        infoJsonObject.put("infolist", newtrarray);
                        for (WebElement newtrElement : newtrsElement) {
                            List<WebElement> newtdsElement = newtrElement.findElements(By.tagName("td"));
                            JSONObject newtdjson = new JSONObject();
                            newtdjson.put("operate", newtdsElement.get(0).getText());
                            newtdjson.put("operateaddress", newtdsElement.get(1).getText());
                            newtdjson.put("date", newtdsElement.get(2).getText());
                            newtdjson.put("time", newtdsElement.get(3).getText());
                            newtdjson.put("transport", newtdsElement.get(4).getText());
                            newtdjson.put("hc", newtdsElement.get(5).getText());
                            newtrarray.add(newtdjson);
                        }


                        Object[] strList = newDriver.getWindowHandles().toArray();

                        newDriver.close();
                        newDriver.quit();
                    }

                    jedis.sadd("so:hlc:"+bkNo+":reslut",arrayJson.toString());
                    System.out.println(arrayJson.toString());

        }catch(Exception e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        HLCServiceThread thread  =  new  HLCServiceThread();
        thread.run();
    }


}

BaseService.java

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by pengweikang on 2018/1/24.
 */
@Component
public  abstract  class BaseService  implements  Runnable{
    public PhantomJSDriver getDriver(){
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        //截屏支持
        dcaps.setCapability("takesScreenshot", true);
        //css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        dcaps.setCapability("phantomjs.page.settings.XSSAuditingEnabled",true);
        dcaps.setCapability("phantomjs.page.settings.webSecurityEnabled",false);
        dcaps.setCapability("phantomjs.page.settings.localToRemoteUrlAccessEnabled",true);
        dcaps.setCapability("phantomjs.page.settings.XSSAuditingEnabled",true);

       dcaps.setCapability("phantomjs.page.settings.loadImages",false);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,  System.getProperty(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY));
        //dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,systemProps.getPhantomjsPath());

        //dcaps.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        //dcaps.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101   Firefox/50.0");
        dcaps.setCapability("ignoreProtectedModeSettings", true);
//        org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
//        proxy.setProxyType(org.openqa.selenium.Proxy.ProxyType.MANUAL);
//        proxy.setHttpProxy("http://180.155.128.87:47593/");
//        dcaps.setCapability(CapabilityType.PROXY, proxy);




        //创建无界面浏览器对象
        PhantomJSDriver driver = new PhantomJSDriver(dcaps);
        driver.manage().timeouts().pageLoadTimeout(120,TimeUnit.SECONDS);
        driver.manage().timeouts().setScriptTimeout(120,TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.manage().deleteAllCookies();
        driver.manage().window().setSize(new Dimension(1920,1080));
        return driver;
    }




    public boolean initOk(WebDriver driver,int CheckTImes, By by){

        int index = CheckTImes;

        while(index > 0){

            try {
                System.out.println(driver.getPageSource());
                WebElement element = driver.findElement(by);
                if(element != null){
                    return true;
                }
            }catch ( Exception e){

            }finally {

            }

            try {
                Thread.sleep(5000);
            }catch (Exception e){

            }

            index --;
        }
        return false;
    }
    public void setProxy(PhantomJSDriver driver){

    }

}

RedisUtils.java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.*;

/**
 * Created by pengweikang on 2018/1/22.
 */
public class RedisUtils {

    //Redis服务器IP
    private static String ADDR = "127.0.0.1";

    //Redis的端口号
    private static int PORT = 6379;

    //访问密码
    private static String AUTH = "admin";

    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;

    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;

    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 10000;

    private static int TIMEOUT = 10000;

    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxWaitMillis(MAX_WAIT);
            //config.setMaxActive(MAX_ACTIVE);
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
           // config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }




    //序列化
    public static byte [] serialize(Object obj){
        ObjectOutputStream obi=null;
        ByteArrayOutputStream bai=null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt=bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    //反序列化
//    public static Object unserizlize(byte[] byt){
//        ObjectInputStream oii=null;
//        ByteArrayInputStream bis=null;
//        bis=new ByteArrayInputStream(byt);
//        try {
//            oii=new ObjectInputStream(bis);
//            Object obj=oii.readObject();
//            return obj;
//        } catch (Exception e) {
//
//            e.printStackTrace();
//        }
//        return null;
//    }


    //反序列化
    public static <T> T  unserizlizeToObject(byte[] byt,Class<T> clazz){
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;
        bis=new ByteArrayInputStream(byt);
        try {
            oii=new ObjectInputStream(bis);
            T obj=(T)oii.readObject();
            return obj;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }



}

UrlParamsUtils.java

import com.alibaba.fastjson.JSONObject;

/**
 * Created by pengweikang on 2018/1/24.
 */
public class UrlParamsUtils {



    public static JSONObject getParams(String url){


        JSONObject jsonObject = new JSONObject();
        String paramUrl = url.substring(url.indexOf("?")+1,url.length());

        String indexUrl = url.substring(0,url.indexOf("?"));
        jsonObject.put("indexUrl",indexUrl);

        String paramObj [] = paramUrl.split("&");



        for(String obj : paramObj){
            String [] keyvalue = obj.split("=");
            jsonObject.put(keyvalue[0],keyvalue[1]);
        }

        return  jsonObject;

    }


}





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/89658
推荐阅读
相关标签
  

闽ICP备14008679号