📜 ⬆️ ⬇️

What we should parse site. Webdriver API Basics

Search for housing , information about products, vacancies, acquaintances , comparison of the company's products with competitors, research of reviews in the network.



The Internet has a lot of useful information and the ability to extract data will help in life and work. Learn how to get information using the webdriver API. In the publication I will give two examples whose code is available on github. At the end of the article is a screencast about how the program manages the browser.

A program or a script with the help of a web driver controls your browser - performs text input, clicking on links, clicking on an element, extracting data from the page and its elements, taking screenshots of the site, etc.
')
To work webdriver you need two components: a browser / server protocol and the client part in the form of a library for your programming language.

You can use the webdriver API from different programming languages ​​and virtual machines: there are official webdriver clients for C #, Ruby, Python, Javascript (Node), as well as clients from the community for Perl, Perl 6, PHP, Haskell, Objective-C, Javascript , R, Dart, Tcl.

Webdriver is currently the W3C standard that is still being worked on . Initially, the Webdriver API appeared in the selenium project for testing purposes, as a result of the evolution of the Selenium-RC API.

As a server, a separate process “understands” the protocol language is used. This process controls your browser. The following drivers are available:


Two drivers stand out from this list:


The essence of technology ...


Minimum theory for further work. Sequence of actions in the client


So, our choice of phantomjs . This is a full-fledged browser, which is controlled by the webdriver protocol. You can run many of its processes at the same time, the graphics subsystem is not required, javascript is fully executed inside (in contrast with the restrictions of htmlunit). If you write scripts in javascript and pass it as a parameter at startup, then phantomJS can execute them without the protocol web driver and even debugging is available using another browser.



Described below refers mostly to the API for java / groovy. In clients of other languages, the list of functions and parameters should be similar.

We get a server with a web driver.


String phantomJsPath = PhantomJsDowloader.getPhantomJsPath() 

Loads phantomjs from maven repository, unpacks and returns the path to this browser. To use, you need to connect to the project library from maven: com.github.igor-suhorukov: phantomjs-runner: 1.1.

You can skip this step if you have previously installed a web driver for your browser in the local file system.

Create a client, connect to the server


 WebDriver driver = new PhantomJSDriver(settings) 

Configures the port for interaction via webdriver protocol, starts the phantomjs process and connects to it.

Open the desired page in the browser


 driver.get(url) 

Opens the page for the specified address in the browser.

We get information of interest to us


 WebElement leftmenu = driver.findElement(By.id("leftmenu")) List<WebElement> linkList = leftmenu.findElements(By.tagName("a")) 

The driver instance and the item derived from it have two useful methods: findElement, findElements. The first returns an item or throws a NoSuchElementException if the item is not found. The second returns a collection of items.

Elements can be selected by the following queries org.openqa.selenium.By:


I will actively use id, tagName and xpath. For those not familiar with xpath - I recommend to look at examples or articles, and only then go on to read the specification.

Perform actions on items on the page and on the page.


You can do the following with an element:


 driver.getScreenshotAs(type) 

Takes a snapshot of the browser window. A useful addition to the standard snapshot function is to recommend the aShot library - it allows you to take a snapshot of only a specific item in a window and allows you to compare items as images.

Screenshots can be obtained as:


Close browser connection


 driver.quit() 

Closes the connection by protocol and in our case stops the phantomjs process.

Example 1: Walking groovy script on social network profiles


Run the command:

 java -jar groovy-grape-aether-2.4.5.1.jar crawler.groovy http://??.com/catalog.php 

Links to the necessary files to run:

The script in the console prints the path to the html file, which is based on information from the social network. In the page you will see the user name, the time of the last visit to the social network and a screenshot of the entire user page.

Why run a script with groovy-grape-aether-2.4.5.1
Groovy -grape-aether-2.4.5.1.jar recently talked about assembling a groove in an article titled “Street Magic in Scripts or what does Groovy, Ivy and Maven connect?” . The main difference from groovy-all-2.4.5.jar is the ability of the Grape mechanism to work with repositories in a more correct way compared to ivy , using the aether library, as well as having access classes to the repositories in the assembly.

crawler.groovy
 package com.github.igorsuhorukov.phantomjs @Grab(group='commons-io', module='commons-io', version='2.2') import org.apache.commons.io.IOUtils @Grab(group='com.github.detro', module='phantomjsdriver', version='1.2.0') import org.openqa.selenium.* import org.openqa.selenium.phantomjs.PhantomJSDriver import org.openqa.selenium.phantomjs.PhantomJSDriverService import org.openqa.selenium.remote.DesiredCapabilities @Grab(group='com.github.igor-suhorukov', module='phantomjs-runner', version='1.1') import com.github.igorsuhorukov.phantomjs.PhantomJsDowloader public class Crawler { public static final java.lang.String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" public static void run(String baseUrl) { def phantomJsPath = PhantomJsDowloader.getPhantomJsPath() def DesiredCapabilities settings = new DesiredCapabilities() settings.setJavascriptEnabled(true) settings.setCapability("takesScreenshot", true) settings.setCapability("userAgent", com.github.igorsuhorukov.phantomjs.Crawler.USER_AGENT) settings.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomJsPath) def WebDriver driver = new PhantomJSDriver(settings) def randomUrl = null def lastVisited=null def name=null boolean pass=true while (pass){ try { randomUrl = getUrl(driver, baseUrl) driver.get(randomUrl) def titleElement = driver.findElement(By.id("title")) lastVisited = titleElement.findElement(By.id("profile_time_lv")).getText() name = titleElement.findElement(By.tagName("a")).getText() pass=false } catch (NoSuchElementException e) { System.out.println(e.getMessage()+". Try again.") } } String screenshotAs = driver.getScreenshotAs(OutputType.BASE64) File resultFile = File.createTempFile("phantomjs", ".html") OutputStreamWriter streamWriter = new OutputStreamWriter(new FileOutputStream(resultFile), "UTF-8") IOUtils.write("""<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body> <p>${name}</p><p>${lastVisited}</p> <img alt="Embedded Image" src="data:image/png;base64,${screenshotAs}"></body> </html>""", streamWriter) IOUtils.closeQuietly(streamWriter) println "html ${resultFile} created" driver.quit(); } static String getUrl(WebDriver driver, String baseUrl) { driver.get(baseUrl) def elements = driver.findElements(By.xpath("//div[@id='content']//a")) def element = elements.get((int) Math.ceil(Math.random() * elements.size())) String randomUrl = element.getAttribute("href") randomUrl.contains("catalog") ? getUrl(driver, randomUrl) : randomUrl } } Crawler.run(this.args.getAt(0)) 

Well-versed grunts will notice that Geb is a better solution. But since it hides all the work with webdriver behind its DSL, Geb is not suitable for our educational purposes. For aesthetic reasons, I agree with you!

Example 2: Retrieving project data from a java-source java program


An example is available here . To run it, java8 is needed, since streams and try-with-resources are used.

 git clone https://github.com/igor-suhorukov/java-webdriver-example.git mvn clean package -Dexec.args="http://java-source.net" 

In this example, I use xpath and axis to extract information from the page. As an example, a fragment of the Project class.

 WebElement main = driver.findElement(By.id("main")); name = main.findElement(By.tagName("h3")).getText(); description = main.findElement(By.xpath("//h3/following-sibling::table/tbody/tr/td[1]")).getText(); link = main.findElement(By.xpath("//td[text()='HomePage']/following-sibling::*")).getText(); license = main.findElement(By.xpath("//td[text()='License']/following-sibling::*")).getText(); 

Part of the data extracted from the site. Files projects.xml - the result of the program
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <projects source="http://java-source.net"> <category> <category>Open Source Ajax Frameworks</category> <project> <name>DWR</name> <description>DWR is a Java open source library which allows you to write Ajax web sites. It allows code in a browser to use Java functions running on a web server just as if it was in the browser. DWR works by dynamically generating Javascript based on Java classes. The code does some Ajax magic to make it feel like the execution is happening on the browser, but in reality the server is executing the code and DWR is marshalling the data back and forwards.</description> <license>Apache Software License</license> <link>http://getahead.org/dwr</link> </project> <project> <name>Google Web Toolkit</name> <description>Google Web Toolkit (GWT) is an open source Java software development framework that makes writing AJAX applications like Google Maps and Gmail easy for developers who don't speak browser quirks as a second language. Writing dynamic web applications today is a tedious and error-prone process; you spend 90% of your time working around subtle incompatibilities between web browsers and platforms, and JavaScript's lack of modularity makes sharing, testing, and reusing AJAX components difficult and fragile. GWT lets you avoid many of these headaches while offering your users the same dynamic, standards-compliant experience. You write your front end in the Java programming language, and the GWT compiler converts your Java classes to browser-compliant JavaScript and HTML.</description> <license>Apache Software License</license> <link>http://code.google.com/webtoolkit/</link> </project> <project> <name>Echo2</name> <description>Echo2 is the next-generation of the Echo Web Framework, a platform for developing web-based applications that approach the capabilities of rich clients. The 2.0 version holds true to the core concepts of Echo while providing dramatic performance, capability, and user-experience enhancements made possible by its new Ajax-based rendering engine.</description> <license>Mozilla Public License</license> <link>http://www.nextapp.com/platform/echo2/echo/</link> </project> <project> <name>ICEfaces</name> <description>ICEfaces is an integrated Ajax application framework that enables Java EE application developers to easily create and deploy thin-client rich Internet applications (RIA) in pure Java. ICEfaces leverages the entire standards-based Java EE ecosystem of tools and execution environments. Rich enterprise application features are developed in pure Java, and in a pure thin-client model. There are no Applets or proprietary browser plug-ins required. ICEfaces applications are JavaServer Faces (JSF) applications, so Java EE application development skills apply directly and Java developers are isolated from doing any JavaScript related development.</description> <license>Mozilla Public License</license> <link>http://www.icefaces.org</link> </project> <project> <name>SweetDEV RIA</name> <description>SweetDEV RIA is a complete set of world-class Ajax tags in Java/J2EE. It helps you to design Rich GUI in a thin client. SweetDEV RIA provides you Out-Of-The-Box Ajax tags. Continue to develop your application with frameworks like Struts or JSF. SweetDEV RIA tags can be plugged into your JSP pages.</description> <license>Apache Software License</license> <link>http://sweetdev-ria.ideotechnologies.com</link> </project> <project> <name>ItsNat, Natural AJAX</name> <description>ItsNat is an open source (dual licensed GNU Affero General Public License v3/commercial license for closed source projects) Java AJAX Component based Web Framework. It offers a natural approach to the modern Web 2.0 development. ItsNat simulates a Universal W3C Java Browser in the server. The server mimics the behavior of a web browser, containing a W3C DOM Level 2 node tree and receiving W3C DOM Events using AJAX. Every DOM server change is automatically sent to the client and updated the client DOM accordingly. Consequences: pure (X)HTML templates and pure Java W3C DOM for the view logic. No JSP, no custom tags, no XML meta-programming, no expression languages, no black boxed components where the developer has absolute control of the view. ItsNat provides an, optional, event based (AJAX) Component System, inspired in Swing and reusing Swing as far as possible such as data and selection models, where every DOM element or element group can be easily a component.</description> <license>GNU General Public License (GPL)</license> <link>http://www.itsnat.org</link> </project> <project> <name>ThinWire</name> <description>ThinWire is an development framework that allows you to easily build applications for the web that have responsive, expressive and interactive user interfaces without the complexity of the alternatives. While virtually any web application can be built with ThinWire, when it comes to enterprise applications, the framework excels with its highly interactive and rich user interface components.</description> <license>GNU Library or Lesser General Public License (LGPL)</license> <link>http://www.thinwire.com/</link> </project> </category> <category> <category>Open Source Aspect-Oriented Frameworks</category> <project> <name>AspectJ</name> <description>AspectJ is a seamless aspect-oriented extension to the Java programming language, Java platform compatible and easy to learn and use. AspectJ enables the clean modularization of crosscutting concerns such as: error checking and handling, synchronization, context-sensitive behavior, performance optimizations, monitoring and logging, debugging support, multi-object protocols.</description> <license>Mozilla Public License</license> <link>http://eclipse.org/aspectj/</link> </project> <project> <name>AspectWerkz</name> <description>AspectWerkz is a dynamic, lightweight and high-performant AOP framework for Java. AspectWerkz offers both power and simplicity and will help you to easily integrate AOP in both new and existing projects. AspectWerkz utilizes runtime bytecode modification to weave your classes at runtime. It hooks in and weaves classes loaded by any class loader except the bootstrap class loader. It has a rich and highly orthogonal join point model. Aspects, advices and introductions are written in plain Java and your target classes can be regular POJOs. You have the possibility to add, remove and re-structure advice as well as swapping the implementation of your introductions at runtime. Your aspects can be defined using either an XML definition file or using runtime attributes.</description> <license>GNU Library or Lesser General Public License (LGPL)</license> <link>http://aspectwerkz.codehaus.org/</link> </project> <project> <name>Nanning</name> <description>Nanning Aspects is a simple yet scaleable aspect-oriented framework for Java.</description> <license>BSD License</license> <link>http://nanning.codehaus.org/</link> </project> <project> <name>JBossAOP</name> <description>JBoss-AOP allows you to apply interceptor technology and patterns to plain Java classes and Dynamic Proxies. It includes: * Java Class Interception. Field, constructor, and method interception, public, private, protected, and package protected, static and class members. * Fully compositional pointcuts caller side for methods and constructors, control flow, annotations. * Aspect classes Advices can be incapsulated in scoped Java classes * Hot-Deploy. Interceptors can be deployed, undeployed, and redeployed at runtime for both dynamic proxies and classes.(working) * Introductions. The ability to add any arbitrary interface to a Java class. Either an interceptor or a 'mixin' class can service method calls for the attached interfaces. * Dynamic Proxies. The ability to define a dynamic proxy and an interceptor chain for it. Proxies can either be created from an existing class, or from a set of interfaces ala java.lang.reflect.Proxy. * Metadata and Attribute Programming. The ability to define and attach metadata configuration to your classes or dynamic proxies. Interceptors can be triggered when metadata is added to a class. We also have Metadata Chains, the ability to define defaults at the cluster and application level, as well as the ability to override configuration at runtime for a specific method call. * Dynamic AOP. All aspected objects can be typecasted to an AOP api. You can do things like add/remove new interceptors to a specific instance or add/remove instance configuration/metadata at runtime.</description> <license>GNU Library or Lesser General Public License (LGPL)</license> <link>http://www.jboss.org/products/aop</link> </project> <project> <name>dynaop</name> <description>dynaop, a proxy-based Aspect-Oriented Programming (AOP) framework, enhances Object-Oriented (OO) design in the following areas: code reuse decomposition dependency reduction</description> <license>Apache Software License</license> <link>https://dynaop.dev.java.net/</link> </project> <project> <name>CAESAR</name> <description>CAESAR is a new aspect-oriented programming language compatible to Java, that is, all Java programs will run with CAESAR.</description> <license>GNU General Public License (GPL)</license> <link>http://caesarj.org/</link> </project> <project> <name>EAOP</name> <description>Event-based Aspect-Oriented Programming (EAOP) for Java. EAOP 1.0 realizes the EAOP model through the following characteristics: * Expressive crosscuts: execution points can be represented by events and crosscuts can be expressed which denote arbitrary relations between events. * Explicit aspect composition: Aspects may be combined using a (extensible) set of aspect composition operators. * Aspects of aspects: Aspects may be applied to other aspects. * Dynamic aspect management: Aspects may be instantiated, composed and destroyed at runtime.</description> <license>GNU General Public License (GPL)</license> <link>http://www.emn.fr/x-info/eaop/tool.html</link> </project> <project> <name>JAC</name> <description>JAC (Java Aspect Components) is a project consisting in developing an aspect-oriented middleware layer.</description> <license>GNU Library or Lesser General Public License (LGPL)</license> <link>http://jac.objectweb.org/</link> </project> <project> <name>Colt</name> <description>Open Source Libraries for High Performance Scientific and Technical Computing in Java</description> <license>The Artistic License</license> <link>http://hoschek.home.cern.ch/hoschek/colt/</link> </project> <project> <name>DynamicAspects</name> <description>DynamicAspects enables you to do aspect-oriented programming in pure Java. Using the \"instrumentation\" and \"agent\" features introduced with Sun JDK 1.5, aspects can be installed and deinstalled during runtime!</description> <license>BSD License</license> <link>http://dynamicaspects.sourceforge.net/</link> </project> <project> <name>PROSE</name> <description>The PROSE system (PROSE stands for PROgrammable extenSions of sErvices) is a dynamic weaving tool (allows inserting and withdrawing aspects to and from running applications) PROSE aspects are regular JAVA objects that can be sent to and be received from computers on the network. Signatures can be used to guarantee their integrity. Once an aspect has been inserted in a JVM, any occurrence of the events of interest results in the execution of the corresponding aspect advice. If an aspect is withdrawn from the JVM, the aspect code is discarded and the corresponding interception(s) will no longer take place.</description> <license>Mozilla Public License</license> <link>http://prose.ethz.ch/Wiki.jsp?page=AboutProse</link> </project> <project> <name>Azuki Framework</name> <description>The Azuki Framework is a java application framework, designed to reduce the development, deployment and maintenance costs of software systems. The Azuki Framework provides also an unique combination of powerful design patterns (decorator, injection, intercepter, command, proxy...). It provides a rapid application assembly from known components in order to build large systems. The software conception is split into two main stages : * Creation of independent components (technical & business service). * Definition of component dependencies (weaving)</description> <license>GNU Library or Lesser General Public License (LGPL)</license> <link>http://www.azuki-framework.org/</link> </project> <project> <name>CALI</name> <description>CALI is a framework to prototype and compose Aspect-Oriented Programming Languages on top of Java. It is based on an abstract aspect language that its extensible to implement new AOPL. As proof of approach and methodology, the following language have been implemented: -AspectJ (Dynamic part of AspectJ, where intertype declartion can be implemented using regular AspectJ); -EAOPJ : An implementation of Event-Based AOP for Java; -COOL: A DSAL for coordination; -Decorator DSAL. You can use CALI to implement your new AOPL and compose it with existing implementation or using existing implementation to write your applications with aspects form different AOPL.</description> <license>Other</license> <link>http://www.emn.fr/x-info/cali/</link> </project> </category> </projects> 


This is how the same example works with the ChromeDriver driver (org.seleniumhq.selenium: selenium-chrome-driver: 2.48.2). Unlike PhantomJS, in this case, you can see what happens during the launch of the program: following links, page rendering.



Conclusion


Webdriver API can be used from different programming languages. It is quite simple to write a script or program to control the browser and extract information from the pages: it is convenient to receive data from the page by Id tag, CSS selector or XPath expression. It is possible to take pictures of the page and individual elements on it. Based on examples and documentation, you can develop scripts of almost any complexity for working with the site. For development and debugging it is better to use a regular browser and web driver for it. PhantomJS is better suited for fully automatic operation.

Good luck in extracting open and useful information from the web!

Source: https://habr.com/ru/post/272105/


All Articles