Code Monkey home page Code Monkey logo

erik's Introduction

Erik

Join the chat at https://gitter.im/phimage/Erik License Platform Language Issues CocoapodCarthage compatible

Become a Patron! Buy me a coffee

Erik is a headless browser based on WebKit and HTML parser Kanna.

An headless browser allow to run functional tests, to access and manipulate webpages using javascript.

let browser = Erik.visit(url: url) { document, error in
    // browse HTML element, click, submit form and more
}

Navigation

Go to an url

Erik.visit(url: url) { object, error in
    if let e = error {

    } else if let doc = object {
        // HTML Inspection
    }
}

How to get current url?

if let url = Erik.currentURL {..}

For multiple browsing you can create an instance of headless browser and use same functions

let browser = Erik()
browser.visitURL...

HTML Inspection

Search for nodes by CSS selector

for link in doc.querySelectorAll("a, link") {
    print(link.text)
    print(link["href"])
}

Edit first input field with name "user"

if let input = doc.querySelectorAll("input[name=\"user\"]").first {
    input["value"] = "Eric"
}

Submit a form

if let form = doc.querySelector("form[id='search']") as? Form {
    form.submit()
}

Evaluate some JavaScript

let javaScriptSource = "console.log("test");"
Erik.evaluate(javaScript:javaScriptSource) { (obj, err) -> Void in
    if let error = err {
        switch error {
            case ErikError.javaScriptError(let message):
            print(message)
            default :
            print("\(error)")
        }
    }
    else if let capturedValue = obj {
        // do something according to result
    }
}

capturedValue is the content of JavaScript variable resultErik Affect this variable in your JavaScript code.

let javaScriptSource = "console.log('test'); var resultErik = 1 + 1;"

Warning about DOM change

⚠️ All action on Dom use JavaScript and do not modify the actual Document object and its children Element.

You must use currentContent to get a refreshed Document object

Get current content

Erik.currentContent { (obj, err) -> Void in
    if let error = err {
    }
    else if let document = obj {
       // HTML Inspection
    }
}

Using Future

As an optional feature, you can use Future/Promise ( Erik use frameworks BrightFutures & Result)

Example to submit a google search

let url = NSURL(string:"https://www.google.com")!
let value = "Erik The Phantom of Opera"
// visit
var future: Future<Document, NSError> = Erik.visitFuture(url: url)
// fill input field
future = future.flatMap { document -> Future<Document, NSError> in
    if let input = document.querySelector("input[name='q']") {
        input["value"] = value
    }
    if let form = document.querySelector("form[name=\"f\"]") as? Form {
        form.submit()
    }
    return Erik.currentContentFuture()
}
// finally get final result as success or error
future.onSuccess { document in
    // parse result
}
future.onFailure { error in
    print("\(error)")
}

Limitation

On iOS 9 and macOS 10.11, you need to ensure you use https://, because iOS 9 and macOS 10.11 do not like apps sending or receiving data insecurely. If this something you want to override, click here to read about App Transport Security.

Links

Setup

Using cocoapods

CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.

  1. Add the project to your Podfile.

    use_frameworks!
    
    pod 'Erik'
    // or specific target
    target :test do
       pod 'Erik'
    end
  2. Run pod install and open the .xcworkspace file to launch Xcode.

Optional Future

Add pod 'Erik/Future' to your Podfile and run pod install.

Using carthage

Carthage is a decentralized dependency manager for Objective-C and Swift.

  1. Add the project to your Cartfile.

    github "phimage/Erik"
    

Roadmap

  • (WIP) WKWebView screenshot (webkit view privates api?)

Why Erik?

A well known headless browser is named PhantomJS and a very well known browser is Opera.

As a tribute I use Erik, firstname of the title character from Gaston Leroux's novel Le Fantôme de l'Opéra best known to English speakers as The Phantom of Opera

My name is also Erik. So egotistical to call a project using its firstname isn't it.

My only justification is that I was playing Metal Gear Solid V and the creator Hideo Kojima name appears over 100 times in the game. Coincidentally the full name of the game is Metal Gear Solid V : The Phantom Pain.

License

The MIT License. See the LICENSE file for more information.

erik's People

Contributors

ahmed-shehata avatar catalandres avatar chinsyo avatar delebedev avatar e-marchand avatar joedf avatar matadan avatar nvprokofiev avatar phimage avatar ziadtamim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

erik's Issues

How does it work ?

Sorry for this idiot question but, i dont know how it works.

When i try to do :

Erik.visitURL(NSURL(string: "https://google.com")!) { document, error in
            // browse HTML element, click, submit form and more
            print(document)
            print(error)
}

the output is empty markup html :

Optional(<html><head></head><body></body></html>)
nil

I dont know if is it normal behaviour or anything else i have forgotten.

Can't install pod properly: "No such module 'Erik'"

Hello,

I'm trying to use Erik..
First I tried pod try Erik and selected the first demo application, but this gave me the following error:

[!] Unable to satisfy the following requirements:

- `FileKit (from `https://github.com/nvzqz/FileKit.git`, branch `develop`)` required by `Podfile`

Then I tried to install Erik into a new Xcode project (xcode 9, iOS 11). Here's the pod file I used:

target 'ErikPlayAgain' do
  use_frameworks!

  pod 'Erik'
end

When opening the project I get 22 error, even without import Erik. All errors in Kanna.switf that look very similar to this:
Let 'kDefaultXmlParseOption' is private and cannot be referenced from a default argument value.
When import Erik to my ViewController, I see this: No such module 'Erik'.

This is a very trivial task, but I still can't make it work. What am I missing?

Newboy question

I new at Swift and faced with some errors after adding you framework/library. Can you help me?
xCode: 9.4.1
Cocoapods: 1.5.3
Swift: 3.3/4.1 (both with the same errors)

Alt text

Could not build Objective-C module 'libxml2'

I encountered following error trying to build Erik on an empty iOS project using CocoaPods.

<module-includes>:1:9: note: in file included from <module-includes>:1:
#import "libxml2-kanna.h"
        ^
/Users/gbm/Developer/Study/TestApp/Pods/Kanna/Modules/libxml2-kanna.h:1:9: note: in file included from /Users/gbm/Developer/Study/TestApp/Pods/Kanna/Modules/libxml2-kanna.h:1:
#import <libxml2/libxml/HTMLtree.h>
        ^
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.2.sdk/usr/include/libxml2/libxml/HTMLtree.h:15:10: error: 'libxml/xmlversion.h' file not found
#include <libxml/xmlversion.h>
         ^
<unknown>:0: error: could not build Objective-C module 'libxml2'

After some searching, I fixed the problem by adding $(SDKROOT)/usr/include/libxml2 to
Pod project -> Erik target -> Build Settings -> Header Search Path

Podfile.lock

PODS:
  - Erik (2.0.0):
    - Erik/Core (= 2.0.0)
    - Kanna
  - Erik/Core (2.0.0):
    - Kanna
  - Kanna (2.1.1)

macOS Version 10.12.3
Xcode Version 8.2.1

Package Resolution Errors with Erik / Filekit

Hey,

Still trying to incorporate Erik into my project, and am running into package resolution errors on XCode 11.4. I'm running a Kitura/Postgresql/Swift-Kuery-ORM project and get the following message when trying to add Erik:

because Erik >=5.1.0 depends on FileKit 6.0.0..<7.0.0 and Configuration >=3.0.0 depends on FileKit 0.0.1..<1.0.0, Erik is incompatible with Configuration.
And because Swift-cfenv >=6.0.0 depends on Configuration 3.0.0..<4.0.0 and every version of Kitura-OpenAPI depends on Swift-cfenv 6.0.0..<7.0.0, Erik is incompatible with Kitura-OpenAPI.
And because root depends on Kitura-OpenAPI 1.1.1..<2.0.0 and root depends on Erik 5.1.0..<5.2.0, version solving failed.

Looks like a wide disparity between https://github.com/IBM-Swift/Configuration and Erik, but I'm still new at this and might be confused.

Overriding navigationDelegate causes ErikError.noContent

Overriding navigationDeledate causes ErikError.noContent,
if you remove the view.navigationDelegate = self line then it content is produced.

class Test: LayoutEngineNavigationDelegate {
    let view: WKWebView
    let browser: Erik
    
    override init() {
        view = WKWebView()
        browser = Erik(webView: view)
        super.init()
        view.navigationDelegate = self
    }
    
    func test() {
        browser.visit(url: URL(string: "https://google.com")!) { (document, err) in
            debugPrint(err as Any)
            debugPrint(document as Any)
        }
    }
}

Another Noob Question

I'm using XCode 11 and a package.swift file to configure my project. I'd rather keep using this, since it's what I'm familiar with.

When adding phimage/Erik.git to the package file, I get the following error:

https://github.com/phimage/Erik.git has no Package.swift manifest for version 1.1.1

Is this my error, or something on the Erik side?

Runloop blocks the current thread

As stated in Apple Docs:

The RunLoop class is generally not considered to be thread-safe and its methods should only be called within the context of the current thread. You should never try to call the methods of an RunLoop object running in a different thread, as doing so might cause unexpected results.

I have noticed that the completion handler handleLoadRequestCompletion sometimes fails to continue sporadically, I have traced it down to the Runloop func, is this even needed in an iOS setup?

Not navigating to a url

I tried navigating to a url using the:

let browser = Erik.visitURL(url) { document, error in
print(document)
}

snippet, and after testing, the request isn't even made. the only domain i have managed to get was "google.com".
Any help?

Carthage error (Task failed with exit code 65)

Build using Carthage fails with exit code 65.
Tried with both Swift 4 and 4.2 projects and Xcode versions 10.0 and 10.1.
Edit: Tried on another computer aswell.

*** Building scheme "Kanna" in Kanna.xcodeproj
*** Building scheme "BrightFutures-iOS" in BrightFutures.xcworkspace
*** Building scheme "Erik" in Erik.xcworkspace
Build Failed
	Task failed with exit code 65:
	/usr/bin/xcrun xcodebuild -workspace /<project path>/Carthage/Checkouts/Erik/Erik.xcworkspace -scheme Erik -configuration Release -derivedDataPath /Users/<username>/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A255/Erik/4.2.0 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/gb/1_y_9w2x2gj_9y0fb58p691m0000gn/T/Erik SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /<project path>/Carthage/Checkouts/Erik)

This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/gb/1_y_9w2x2gj_9y0fb58p691m0000gn/T/carthage-xcodebuild.x3d07S.log

Change the timeout

Hi!

Is it possible to change the timeout on the evaluate JS function?
I'm running a promise in the JS so I need to extend the timeout.

Not able to submit a form

Hello :)

Thank you for this amazing project. I'm trying to log in on a Central Authentication Service (i think drupal...) so I have to fill a form with my username and password and then submit the form. I tried to submit the form or click on the button submit (or even both) but erik appears to be stuck on the login page.
I tried to connect with HtmlUnit (Java) and it worked, but I need to do it on an iOS App..
Could someone help me? Here are the snippets :

SWIFT :

url = URL(string:"http://edt.insa-cvl.fr")!
        let username = "username"
        let password = "password"
        // visit
        var future: Future<Document, NSError> = Erik.visitFuture(url: url)
        // fill input field
        future = future.flatMap { doc -> Future<Document, NSError> in
            if let inputUsername = doc.querySelector("input[name=\"username\"]") {
                inputUsername["value"] = username
            }
            
            if let inputPassword = doc.querySelector("input[name=\"password\"]") {
                inputPassword["value"] = password
            }
            
            
            
            if let form = doc.querySelector("form[id=\"fm1\"]") as? Form {
                form.submit()
            }
            
            if let buttonSubmit = doc.querySelector("input[name=\"submit\"]") {
                buttonSubmit.click()
            }

        
            return Erik.currentContentFuture()
        }
        // finally get final result as success or error
        future.onSuccess { doc in
            print(String(describing: doc))
        }
        future.onFailure { error in
            print("\(error)")
        }


JAVA :

try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52)) {
		    final HtmlPage page = webClient.getPage("http://edt.insa-cvl.fr");
		   final HtmlTextInput usernameField = (HtmlTextInput) page.getElementById("username");
		    final HtmlPasswordInput passwordField = (HtmlPasswordInput) page.getElementById("password");
		    
		    usernameField.setValueAttribute("username");
		    passwordField.setValueAttribute("password");
		    
		    final HtmlSubmitInput buttonSubmit = page.getElementByName("submit");
		    final HtmlPage page2 = buttonSubmit.click();
		     
		     System.out.println(page2.asXml());

		}

Thanks in advance!

Could not build Objective-C module 'Erik'

I installed Erik using podfile and the installation is successful, but it gives me this error when I do "import Erik". Below is my podfile.

platform :ios, '12.0'

target 'MyTritonLink' do
use_frameworks!
pod 'Erik'

target 'MyTritonLinkTests' do
inherit! :search_paths
# Pods for testing
end

target 'MyTritonLinkUITests' do
inherit! :search_paths
# Pods for testing
end

end

Carthage and SwiftPM builds fail

Hi,

I tried to install Erik using SwiftPM, but it fails, because BrightFutures doesn't support SwiftPM. Then I tried to install using Carthage, which also fails:

The following build commands failed:
    PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/chris/Library/Developer/Xcode/DerivedData/Erik-dgbtbdospwkecwbjmogzqtvhbkvk/Build/Intermediates/Erik.build/Release-iphoneos/Erik.build/Script-BF088855B5DAF2A7EA705BA7.sh
(1 failure)
ld: warning: linking against a dylib which is not safe for use in application extensions: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/XCTest.framework/XCTest.tbd
ld: warning: linking against a dylib which is not safe for use in application extensions: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/libswiftXCTest.dylib
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
A shell task (/usr/bin/xcrun xcodebuild -workspace /Users/chris/objc.io/bookkeeping/KDPFetch/Carthage/Checkouts/Erik/Erik.xcworkspace -scheme Erik -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/chris/Library/Developer/Xcode/DerivedData/Erik-dgbtbdospwkecwbjmogzqtvhbkvk/Build/Intermediates/Erik.build/Release-iphoneos/Erik.build/Script-BF088855B5DAF2A7EA705BA7.sh
(1 failure)

testSubmit() fails

I cloned the repo and ran tests.

testSubmit() fails. I suspect this is related to #24 and will be fixed with #24.

Please let me know if there is anything I can do to help resolve these.

Threading with promises

Hi

I seem to be having issues with promises. Erik.visit() and Erik.visitFuture() take a very long time when embedded in other promises. And then they eventually fail to provide a document as I think the request is timed out.

I've tried with both BrightFutures and PromiseKit.

Is this possibly a threading issue?

in iOS, If I create multiple instances of Erik and each one loads a URL, it raises an ErikError.timeOutError

Hello. Thanks for the great library.

It seems that if I create multiple instances of Erik and each one loads a URL, it raises an ErikError.timeOutError.
Running the following code on my iPad mini 4 raises an ErikError.timeOutError in most cases.

    let erikPool:[Erik] = [
        Erik(), Erik(), Erik(), Erik(), Erik(),
        Erik(), Erik(), Erik(), Erik(), Erik(),
    ]
    func testErik() {
        guard let url = URL(string: "https://www.google.com/") else { return }
        func startErik(id:String, url:URL, client:Erik) {
            client.visit(url: url) { (doc, err) in
                if let err = err {
                    print("Erik error.", err.localizedDescription)
                    return
                }
                if let firstLine = doc?.innerHTML?.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "\n").first {
                    print(id, "request done.", firstLine)
                }else{
                    print(id, "request done. but no content?")
                }
            }
        }
        for (i, erik) in erikPool.enumerated() {
            startErik(id: String(format: "test #%d", i), url: url, client: erik)
        }
    }

Perhaps it's because the handleLoadRequestCompletion in Erik's WebKitLayoutEngine is busy looping, but it looks like the processing isn't up to speed.
As a workaround to this issue, I added Thread.sleep(forTimeInterval: 0.1) to Erik's source code as shown below, and found that each request completed successfully.

    fileprivate func handleLoadRequestCompletion(completionHandler: (Error?) -> Void) {
        // wait load finish
        let condition = pageLoadedPolicy.continueCondition
        let max = Date().timeIntervalSince1970 + pageLoadTimeout
        while(condition(self)) {
            if pageLoadTimeout > 0 && Date().timeIntervalSince1970 > max  {
                completionHandler(ErikError.timeOutError(time: pageLoadTimeout))
                return
            }
        #if os(OSX)
            RunLoop.current.run(mode: RunLoop.Mode.default, before: Date.distantFuture)
        #else
            Thread.sleep(forTimeInterval: 0.1)
        #endif
        }
        completionHandler(nil)
    }

I wasn't sure why I was using a loop to monitor this part of the code, so I decided to use the above workaround. However, you may be able to change this problem to something like a WKWebView.addObserver that monitors changes in "estimatedProgress" or "loading" without using a busy loop.

[Help needed] Running in Vapor project

Hey! I implemented Erik in my Vapor project and it runs well when I do it on my Mac. But I have a problem with the deployment of the project with Erik to my Linux server - the compilation fails with "no such module WebKit". I've done research and found that there is no easy solution to run WebKit on Linux systems. Honestly, I didn't find any workable one. Can you please give me a hint of how can I do it? Such a disaster when everything works that smoothly on Mac and due to one dependency I can't run it on Linux.

Typo fix

I dont know yet how to create pull request so here a little typo fix :

let browser = Erik.visitURL(url]) { document, error in
    // browse HTML element, click, submit form and more
}

Begin

let browser = Erik.visitURL(url) { document, error in
    // browse HTML element, click, submit form and more
}

Delete right brackets after url param.

Future Plans?

Do you have any of the following items as potential tasks for the future of Erik:

  • Adding a CLI
  • Supporting linux (with swift not going open and working on linux)

These two items will make this a good replacement for phantomjs for CI environments

doc.toHTML only gives last few lines of html

When I print out the doc it only has the last few lines of html code. I have tried doc.body and it works fine. So I am wondering is it the problem of Erik?
p.s. This also happened to the google website. I used the code in the example.

The print statement gives me following:

script>

<script src="/tritON/scripts/bootstrap.js"></script>

<script src="https://www.google.com/cse/brand?form=cse-search-box&amp;lang=en"></script>




</body>
</html>

My code is below:

Erik.visit(url: url) { obj, err in
    if let e = err {
        print("Error: \(e)")
    } else if let doc = obj {
        print(doc.toHTML!)
        if let input = doc.querySelectorAll("input[id='ssousername']").first {
            input["value"] = user
        }
        if let input = doc.querySelectorAll("input[id='ssopassword']").first {
            input["value"] = password
        }
        if let form = doc.querySelector("form[id='login']") as? Form {
            form.submit()
        }
    }
}

Swift 3 support

Trying to compile my app with Swift 3 and I get two errors about unwrapping optionals. I've chosen to use the legacy swift compiler, but I think 2.3 (which is what I assume it's using) is also incompatible.

I need take a screenshot

Hi, you was added screenshot speciality on roadmap but you dont add ass a code can you improve this feature.

UI API called on a background thread - iOS 11 - Xcode 9

Hi!

Erik unfortunately does not work on iOS 11. With the new Main Thread Checker in XCode 9 it prints out the following in the console:

  • Main Thread Checker: UI API called on a background thread: -[WKWebView navigationDelegate]
  • Main Thread Checker: UI API called on a background thread: -[WKWebView evaluateJavaScript:completionHandler:]

Best regards,
Ziad

Question: html -> pdf?

Can Erik be used to generate a PDF file from the rendering of a webpage via either https and/or file url? (preferrably not as a image raster which is then placed into PDF)

Attempted to read an unowned reference but object was already deallocated

Turns out it was my fault, Erik was being deallocated.

=======

While trying to implement LayoutEngineNavigationDelegate I get the following error.

Fatal error: Attempted to read an unowned reference but object 0x283c56000 was already deallocated2021-09-05 06:31:23.406532+1200 TestApp[2841:520580] Fatal error: Attempted to read an unowned reference but object 0x283c56000 was already deallocated
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Fatal error: Attempted to read an unowned reference but object 0x283c56000 was already deallocated

My Code:

    class Test: LayoutEngineNavigationDelegate {
        func test() {
            let view = WKWebView()
            let browser = Erik(webView: view)
            view.navigationDelegate = self
            
            browser.visit(url: URL(string: "https://github.com/")!) { [unowned self] (document, err) in
                debugPrint(err)
                debugPrint(document)
            }
        }
        
        override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
            
            debugPrint(navigationAction.request)
            
            decisionHandler(.allow)
        }
    }

How to update html ?

Are there any sample projects on executive javascript functions and even submitting forms? The example with google search is not working.

Detach Kana

Could you detach kana as optional? so someone want to use other parser could work on this too.

Thank

Erik.visitURLFuture does not exist

Erik.visitURLFuture is in the examples in the README file but it does not exist. Nor does Erik.currentContentFuture.

Is there a missing API?

[Help Needed] wait for site finish loading

Hello, I'm really sorry to bother you, but how can I get the contents of a website after it has finished loading? I've searched everywhere and found nothing. Please help me. :(

Swift 4 support?

Kanna is in beta right now for Swift 4. Is there a possibility for Erik to start in beta?

Website cannot successfully login

I filled in the username and password and click the submit button, but when I examine the html using browser.currentContent I find out that it still stays at the same page. I am not sure if it's the click() method not working. Am I doing anything wrong? Thanks!

private func submit(_ url: URL, user: String, password: String) {
    browser.visit(url: url) { obj, err in
        if let e = err {
            print("Error: \(e)")
        } else if let doc = obj {
            if let input = doc.querySelectorAll("input[id='ssousername']").first {
                input["value"] = user
            }
            if let input = doc.querySelectorAll("input[id='ssopassword']").first {
                input["value"] = password
            }
            _ = doc.click("button[type='submit']")
            }
    }
    browser.currentContent { (obj, err) -> Void in
        if let e = err {
            print("Error: \(e)")
        } else if let doc = obj {
            print(doc.body!)
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.