Best JavaScript code snippet using playwright-internal
0000-functions-payment.js
Source:0000-functions-payment.js
1/**2 * HiPay Enterprise SDK Casper JS3 *4 * 2017 HiPay5 *6 * NOTICE OF LICENSE7 *8 * @author HiPay <support.tpp@hipay.com>9 * @copyright 2017 HiPay10 *11 */12casper.test.begin('Functions', function(test) {13 /**********************************************************/14 /******* FILL ALL HIPAY PAYMENT PAGE ***/15 /**********************************************************/16 casper.fillPaymentFormularByPaymentProduct = function(payment_product) {17 this.echo("Filling payment formular [ " + payment_product +" ]...", "INFO");18 switch (payment_product) {19 case "dexia-directnet":20 this.fillFormDexiaDirectNet();21 break;22 case "3xcb":23 case "4xcb":24 this.fillFormOneyFacilyPay();25 break;26 case "ing-homepay":27 this.fillFormIngHomePay();28 break;29 case "ideal":30 this.fillFormIDeal();31 break;32 case "sofort-uberweisung":33 this.fillFormSofort();34 break;35 case "postfinance-card":36 this.fillFormPostFinance();37 break;38 case "sisal":39 this.fillFormSisal();40 break;41 case "sdd":42 this.fillFormSdd();43 break;44 case "visa":45 this.fillFormCC(payment_product);46 break;47 default:48 test.fail('Filling payment product is not implemented by HiPay SDK Casper JS')49 }50 },51 /**********************************************************/52 /******* HOSTED ***/53 /**********************************************************/54 casper.fillFormCC = function(payment_product) {55 this.waitForUrl(/payment\/web/, function success() {56 this.echo("Filling hosted payment formular...", "INFO");57 this.waitForSelector('input#cardNumber', function success() {58 this.fillCCFormular(payment_product);59 }, function fail() {60 this.echo("VISA input doesn't exists. Checking for select field...", 'WARNING');61 this.waitForSelector('select#payment-product-switcher', function success() {62 this.warn("OK. This payment template is deprecated");63 this.fillSelectors('#form-payment', {64 'select[name="paymentproductswitcher"]': "visa"65 });66 this.fillCCFormular(payment_product);67 }, function fail() {68 test.assertExists('select#payment-product-switcher', "Select field exists");69 });70 });71 }, function fail () {72 test.assertUrlMatch(/payment\/web/, "Payment page exists");73 });74 },75 /* Fill formular according to the template, with or without iframe */76 casper.fillCCFormular = function (payment_product) {77 var holder = "MC",78 month = "12",79 year = "2020",80 code = "500";81 this.wait(5000, function() {82 if(this.exists('iframe#tokenizerFrame')) {83 this.withFrame(0, function() {84 this.fillSelectors('form#tokenizerForm', {85 'input[name="tokenizerForm:cardNumber"]': cardsNumber.VI,86 'input[name="tokenizerForm:cardHolder"]': holder,87 'select[name="tokenizerForm:cardExpiryMonth"]': month,88 'select[name="tokenizerForm:cardExpiryYear"]': year,89 'input[name="tokenizerForm:cardSecurityCode"]': code90 }, false);91 });92 }93 else {94 this.fillSelectors('form#form-payment', {95 'input[name="cardNumber"]': cardsNumber.VI,96 'input[name="cardHolder"]': holder,97 'select[name="cardExpiryMonth"]': month,98 'select[name="cardExpiryYear"]': year,99 'input[name="cardSecurityCode"]': code100 }, false);101 }102 this.thenClick('#submit-button', function() {103 test.info("Done");104 });105 });106 };107 /**********************************************************/108 /******* SDD ***/109 /**********************************************************/110 casper.fillFormSdd = function() {111 this.echo("Filling payment formular...", "INFO");112 this.waitForUrl(/payment\/pay\/reference/, function success() {113 this.fillSelectors('#registrationform', {114 'select[name="gender"]': "male",115 'input[name="firstname"]': "TEST",116 'input[name="lastname"]': "TEST",117 'input[name="street"]': "Rue de la paix",118 'input[name="zip"]': "75000",119 'input[name="city"]': "PARIS",120 'select[name="country"]': "GB",121 'input[name="email"]': "email@yopmail.com"122 }, false);123 this.thenClick('input[name="bankaccountselection"]', function() {124 this.fillSelectors('#registrationform', {125 'input[name="iban"]': ibanNumber.GB,126 'input[name="bic"]': bicNumber[0]127 }, false);128 this.click('body');129 this.waitUntilVisible('div.ajaxsuccess', function success() {130 test.assertNotVisible('div.ajaxerror', "Correct IBAN and BIC number");131 this.click('input#nyrosubmitfix');132 test.info("Done");133 this.echo("Submitting formular...", "INFO");134 }, function fail() {135 test.assertAllVisible('div.ajaxsuccess', "Succesful div block exists");136 });137 });138 }, function fail() {139 test.assertUrlMatch(/payment\/pay\/reference/, "Payment page exists");140 }, 10000);141 },142 /**********************************************************/143 /******* SISAL ***/144 /**********************************************************/145 casper.fillFormSisal = function() {146 this.waitForUrl(/provider\/sisal/, function success() {147 this.click('a#submit-button');148 test.info("Done");149 }, function fail() {150 test.assertUrlMatch(/provider\/sisal/, "Payment page exists");151 }, 10000);152 },153 /**********************************************************/154 /******* POST FINANCE ***/155 /**********************************************************/156 casper.fillFormPostFinance = function() {157 this.waitForUrl(/secure\.ogone/, function success() {158 this.click('input#btn_Accept');159 test.info("Done");160 }, function fail() {161 test.assertUrlMatch(/secure\.ogone/, "Payment page exists");162 }, 10000);163 },164 /**********************************************************/165 /******* SOFORT ***/166 /**********************************************************/167 casper.fillFormSofort = function() {168 this.waitForUrl(/go\/select_country/, function success() {169 this.click('form#WizardForm button');170 this.wait(2000, function() {171 this.waitForUrl(/go\/login/, function success() {172 this.fillSelectors('form#WizardForm', {173 'input[name="data[BackendForm][LOGINNAME__USER_ID]"]': "00000",174 'input[name="data[BackendForm][USER_PIN]"]': "123456789"175 }, false);176 this.click("form#WizardForm button");177 test.info("Credentials inserted");178 this.waitForUrl(/go\/select_account/, function success() {179 this.click("input#account-1");180 this.click("form#WizardForm button");181 test.info("Account selected");182 this.waitForUrl(/go\/provide_tan/, function success() {183 this.fillSelectors('form#WizardForm', {184 'input[name="data[BackendForm][TAN]"]': "12345"185 }, false);186 this.click("form#WizardForm button");187 test.info("TAN code inserted");188 }, function fail() {189 test.assertUrlMatch(/go\/provide_tan/, "Payment TAN page exists");190 },20000);191 }, function fail() {192 test.assertUrlMatch(/go\/select_account/, "Payment account page exists");193 });194 }, function fail() {195 test.assertUrlMatch(/go\/login/, "Payment login page exists");196 });197 });198 }, function fail() {199 test.assertUrlMatch(/go\/select_country/, "Payment country page exists");200 }, 20000);201 },202 /**********************************************************/203 /******* IDEAL ***/204 /**********************************************************/205 casper.fillFormIDeal = function() {206 this.waitForUrl(/payment\/web\/pay/, function success() {207 this.fillSelectors("form#form-payment", {208 'select[name="issuer_bank_id"]': "TESTNL99"209 }, true);210 this.waitForUrl(/paymentscreen\/testmode/, function success() {211 this.click('input[name="final_state"][value="paid"]');212 this.click('#footer button.button');213 test.info("Done");214 }, function fail() {215 test.assertUrlMatch(/paymentscreen\/ideal\/testmode/, "Payment IDeal page exists");216 }, 15000);217 }, function fail() {218 test.assertUrlMatch(/payment\/web\/pay/, "Payment page exists");219 }, 15000);220 },221 /**********************************************************/222 /******* ING HOME PAY ***/223 /**********************************************************/224 casper.fillFormIngHomePay = function() {225 this.waitForUrl(/secure\.ogone/, function success() {226 this.click('input#btn_Accept');227 test.info("Done");228 }, function fail() {229 test.assertUrlMatch(/secure\.ogone/, "Payment Ogone page exists");230 }, 30000);231 },232 /**********************************************************/233 /******* ONEY FACILY PAY ***/234 /**********************************************************/235 casper.fillFormOneyFacilyPay = function() {236 this.waitForUrl(/qefinancement/, function success() {237 this.fillSelectors('form#souscriptionPnf',{238 'select[name="civilite"]' : '1',239 'select[name="jourNaissance"]' : "01",240 'select[name="moisNaissance"]' : "01",241 'select[name="anneNaissance"]' : '1985',242 'select[name="departementNaissance"]' : '001',243 'input[name="lieuNaissance"]' : 'Nantes',244 'input[name="numCarte1"]' : '4974',245 'input[name="numCarte2"]' : '5202',246 'input[name="numCarte3"]' : '9047',247 'input[name="numCarte4"]' : '9170',248 'select[name="moiExpiration"]' : "12",249 'select[name="anneeExpiration"]' : '2020',250 'input[name="nomPorteurCarte"]' : 'TEST',251 'input[name="cryptogramme"]' : '123',252 } ,false)253 this.click('input#conditions-gen');254 this.click('a#bouton-validation-demande')255 test.info("Done");256 }, function fail() {257 test.assertUrlMatch(/qefinancement/, "Payment page exists");258 }, 10000);259 };260 /**********************************************************/261 /******* ONEY BELFIUS ***/262 /**********************************************************/263 casper.fillFormDexiaDirectNet = function() {264 this.waitForUrl(/secure\.ogone/, function success() {265 this.click('input#submit1');266 this.waitForUrl(/netbanking_ACS/, function success() {267 this.click('input#btn_Accept');268 test.info("Done");269 }, function fail() {270 test.assertUrlMatch(/netbanking_ACS/, "Payment Ogone second page exists");271 });272 }, function fail() {273 test.assertUrlMatch(/orderstandard/, "Payment Ogone page exists");274 }, 15000);275 }276 /* Fill HiPayCC formular */277 casper.fillFormPaymentHipayCC = function(type, card) {278 this.fillSelectors('form#tokenizerForm', {279 'input[name="card-number"]': card,280 'input[name="card-holders-name"]': 'Mr Test',281 'input[name="expiry-month"]': '02',282 'input[name="expiry-year"]': '20',283 'input[class="expiry"]': '02 / 20',284 'input[name="cvc"]': '500'285 }, false);286 };287 casper.echo('Functions HiPay library loaded !', 'INFO');288 test.done();...
test-globaleaks-process.js
Source:test-globaleaks-process.js
1var utils = require('./utils.js');2var fs = require('fs');3var path = require('path');4var fileToUpload = path.resolve(__filename);5describe('globaLeaks process', function() {6 var tip_text = 'topsecret';7 var receipts = [];8 var comment = 'comment';9 var comment_reply = 'comment reply';10 var message = 'message';11 var message_reply = 'message reply';12 var receiver_username = "Recipient 1";13 var receiver_password = "ACollectionOfDiplomaticHistorySince_1966_ToThe_Pr esentDay#"14 var login_whistleblower = function(receipt) {15 return protractor.promise.controlFlow().execute(function() {16 var deferred = protractor.promise.defer();17 browser.get('/#/');18 element(by.model('formatted_keycode')).sendKeys(receipt).then(function() {19 element(by.css('[data-ng-click="view_tip(formatted_keycode)"]')).click().then(function() {20 utils.waitForUrl('/status');21 deferred.fulfill();22 });23 });24 return deferred.promise;25 });26 }27 var login_receiver = function(username, password) {28 return protractor.promise.controlFlow().execute(function() {29 var deferred = protractor.promise.defer();30 browser.get('/#/login');31 element(by.model('loginUsername')).element(by.xpath(".//*[text()='" + username + "']")).click().then(function() {32 element(by.model('loginPassword')).sendKeys(password).then(function() {33 element(by.xpath('//button[contains(., "Log in")]')).click().then(function() {34 utils.waitForUrl('/receiver/tips');35 deferred.fulfill();36 });37 });38 });39 return deferred.promise;40 });41 }42 var perform_submission = function(done) {43 browser.get('/#/submission');44 element(by.id('step-receiver-selection')).element(by.id('receiver-0')).click().then(function () {45 element(by.id('step-receiver-selection')).element(by.id('receiver-1')).click().then(function () {46 element(by.id('NextStepButton')).click().then(function () {47 element(by.id('step-0')).element(by.id('step-0-field-0-0-input-0')).sendKeys(tip_text).then(function () {48 if (utils.testFileUpload()) {49 browser.executeScript('angular.element(document.querySelector(\'input[type="file"]\')).attr("style", "opacity:0; visibility: visible;");');50 element(by.id('step-0')).element(by.id('step-0-field-3-0')).element(by.xpath("//input[@type='file']")).sendKeys(fileToUpload).then(function() {51 browser.waitForAngular();52 element(by.id('step-0')).element(by.id('step-0-field-3-0')).element(by.xpath("//input[@type='file']")).sendKeys(fileToUpload).then(function() {53 browser.waitForAngular();54 element(by.id('NextStepButton')).click().then(function () {55 element(by.id('step-1')).element(by.id('step-1-field-0-0-input-0')).click().then(function () {56 var submit_button = element(by.id('SubmitButton'));57 var isClickable = protractor.ExpectedConditions.elementToBeClickable(submit_button);58 browser.wait(isClickable);59 submit_button.click().then(function() {60 utils.waitForUrl('/receipt');61 element(by.id('KeyCode')).getText().then(function (txt) {62 receipts.unshift(txt);63 });64 });65 });66 });67 });68 });69 } else {70 element(by.id('NextStepButton')).click().then(function () {71 element(by.id('step-1')).element(by.id('step-1-field-0-0-input-0')).click().then(function () {72 var submit_button = element(by.id('SubmitButton'));73 var isClickable = protractor.ExpectedConditions.elementToBeClickable(submit_button);74 browser.wait(isClickable);75 submit_button.click().then(function() {76 utils.waitForUrl('/receipt');77 element(by.id('KeyCode')).getText().then(function (txt) {78 receipts.unshift(txt);79 });80 });81 });82 });83 }84 element(by.id('ReceiptButton')).click().then(function() {85 utils.waitForUrl('/status');86 element(by.id('LogoutLink')).click().then(function() {87 utils.waitForUrl('/');88 done();89 });90 });91 });92 });93 });94 });95 }96 it('should redirect to /submission by clicking on the blow the whistle button', function(done) {97 browser.get('/#/');98 element(by.css('[data-ng-click="goToSubmission()"]')).click().then(function () {99 utils.waitForUrl('/submission');100 done();101 });102 });103 it('Whistleblowers should be able to submit tips (1)', function(done) {104 perform_submission(done);105 });106 it('Whistleblowers should be able to submit tips (2)', function(done) {107 perform_submission(done);108 });109 it('Whistleblowers should be able to submit tips (3)', function(done) {110 perform_submission(done);111 });112 it('Whistleblower should be able to access the first submission', function(done) {113 login_whistleblower(receipts[0]).then(function() {114 expect(element(by.xpath("//*[contains(text(),'" + tip_text + "')]")).getText()).toEqual(tip_text);115 element(by.id('LogoutLink')).click().then(function() {116 utils.waitForUrl('/');117 done();118 });119 });120 });121 it('Recipient should be able to access the first submission', function(done) {122 login_receiver(receiver_username, receiver_password).then(function() {123 element(by.id('tip-0')).click().then(function() {124 expect(element(by.xpath("//*[contains(text(),'" + tip_text + "')]")).getText()).toEqual(tip_text);125 done();126 });127 });128 });129 it('Recipient should be able to refresh tip page', function(done) {130 element(by.id('link-reload')).click().then(function () {131 browser.waitForAngular();132 done();133 });134 });135 it('Recipient should be able to see files and download them', function(done) {136 if (utils.testFileUpload()) {137 expect(element.all(by.cssContainingText("button", "download")).count()).toEqual(2);138 if (utils.testFileDownload()) {139 element.all(by.cssContainingText("button", "download")).get(0).click().then(function() {140 browser.waitForAngular();141 done();142 });143 } else {144 done();145 }146 } else {147 done();148 }149 });150 it('Recipient should be able to leave a comment to the whistleblower', function(done) {151 login_receiver(receiver_username, receiver_password).then(function() {152 element(by.id('tip-0')).click().then(function() {153 element(by.model('tip.newCommentContent')).sendKeys(comment);154 element(by.id('comment-action-send')).click().then(function() {155 browser.waitForAngular();156 element(by.id('comment-0')).element(by.css('.preformatted')).getText().then(function(c) {157 expect(c).toContain(comment);158 element(by.id('LogoutLink')).click().then(function() {159 utils.waitForUrl('/login');160 done();161 });162 });163 });164 });165 });166 });167 it('Whistleblower should be able to read the comment from the receiver and reply', function(done) {168 login_whistleblower(receipts[0]).then(function() {169 element(by.id('comment-0')).element(by.css('.preformatted')).getText().then(function(c) {170 expect(c).toEqual(comment);171 element(by.model('tip.newCommentContent')).sendKeys(comment_reply);172 element(by.id('comment-action-send')).click().then(function() {173 browser.waitForAngular();174 element(by.id('comment-0')).element(by.css('.preformatted')).getText().then(function(c) {175 expect(c).toContain(comment_reply);176 done();177 });178 });179 });180 });181 });182 it('Whistleblower should be able to attach a new file to the first submission', function(done) {183 login_whistleblower(receipts[0]).then(function() {184 if (utils.testFileUpload()) {185 browser.executeScript('angular.element(document.querySelector(\'input[type="file"]\')).attr("style", "opacity:0; visibility: visible;");');186 element(by.xpath("//input[@type='file']")).sendKeys(fileToUpload).then(function() {187 browser.waitForAngular();188 element(by.xpath("//input[@type='file']")).sendKeys(fileToUpload).then(function() {189 browser.waitForAngular();190 // TODO: test file addition191 element(by.id('LogoutLink')).click().then(function() {192 utils.waitForUrl('/');193 done();194 });195 });196 });197 } else {198 done();199 }200 });201 });202 it('Recipient should be able to start a private discussion with the whistleblower', function(done) {203 login_receiver(receiver_username, receiver_password).then(function() {204 element(by.id('tip-0')).click().then(function() {205 element(by.model('tip.newMessageContent')).sendKeys(message);206 element(by.id('message-action-send')).click().then(function() {207 browser.waitForAngular();208 element(by.id('message-0')).element(by.css('.preformatted')).getText().then(function(m) {209 expect(m).toContain(message);210 element(by.id('LogoutLink')).click().then(function() {211 utils.waitForUrl('/login');212 done();213 });214 });215 });216 });217 });218 });219 it('Whistleblower should be able to read the private message from the receiver and reply', function(done) {220 login_whistleblower(receipts[0]).then(function() {221 element.all(by.options("obj.key as obj.value for obj in tip.msg_receivers_selector | orderBy:'value'")).get(1).click().then(function() {222 element(by.id('message-0')).element(by.css('.preformatted')).getText().then(function(m) {223 expect(message).toEqual(message);224 element(by.model('tip.newMessageContent')).sendKeys(message_reply);225 element(by.id('message-action-send')).click().then(function() {226 browser.waitForAngular();227 element(by.id('message-0')).element(by.css('.preformatted')).getText().then(function(m) {228 expect(m).toContain(message_reply);229 done();230 });231 });232 });233 });234 });235 });236 it('Recipient should be able to export the submission', function(done) {237 login_receiver(receiver_username, receiver_password).then(function() {238 element(by.id('tip-0')).click().then(function() {239 if (utils.testFileDownload()) {240 element(by.id('tip-action-export')).click().then(function () {241 browser.waitForAngular();242 // TODO: test the downloaded zip file opening it and verifying its content.243 done();244 });245 } else {246 done();247 }248 });249 });250 });251 it('Recipient should be able to postpone first submission from tip page', function(done) {252 login_receiver(receiver_username, receiver_password).then(function() {253 element(by.id('tip-0')).click().then(function() {254 element(by.id('tip-action-postpone')).click().then(function () {255 element(by.id('modal-action-ok')).click().then(function() {256 //TODO: check postpone257 element(by.id('LogoutLink')).click().then(function() {258 utils.waitForUrl('/login');259 done();260 });261 });262 });263 });264 });265 });266 it('Recipient should be able to delete first submission from tip page', function(done) {267 login_receiver(receiver_username, receiver_password).then(function() {268 element(by.id('tip-0')).click().then(function() {269 element(by.id('tip-action-delete')).click().then(function () {270 element(by.id('modal-action-ok')).click().then(function() {271 utils.waitForUrl('/receiver/tips');272 //TODO: check delete273 element(by.id('LogoutLink')).click().then(function() {274 utils.waitForUrl('/login');275 done();276 });277 });278 });279 });280 });281 });282 it('Recipient should be able to postpone all tips', function(done) {283 login_receiver(receiver_username, receiver_password).then(function() {284 element(by.id('tip-action-select-all')).click().then(function() {285 element(by.id('tip-action-postpone-selected')).click().then(function () {286 element(by.id('modal-action-ok')).click().then(function() {287 utils.waitForUrl('/receiver/tips');288 //TODO: check postpone289 element(by.id('LogoutLink')).click().then(function() {290 utils.waitForUrl('/login');291 done();292 });293 });294 });295 });296 });297 });...
crawler.js
Source:crawler.js
1const puppeteer = require("puppeteer");2var moment = require("moment");3let fs = require("fs");4// è½½å
¥æ¨¡å5var Segment = require('segment');6// å建å®ä¾7var segment = new Segment();8// 使ç¨é»è®¤çè¯å«æ¨¡åååå
¸ï¼è½½å
¥åå
¸æ件éè¦1ç§ï¼ä»
åå§åæ¶æ§è¡ä¸æ¬¡å³å¯9segment.useDefault();10segment.loadStopwordDict('./stopword.txt');11let waitForUrl = ["https://www.scut.edu.cn/new/"];12let waitForUrlChild = [];13let processedurl = [];14// é»è®¤æ·±åº¦ -3å±15let deep = Number.MAX_SAFE_INTEGER;16let refrence = {};17// å½å深度18let currdeep = 1;19(async () => {20 const browser = await puppeteer.launch({21 headless: true, //é»è®¤ä¸ºtrueï¼æ 头ï¼ï¼ä¸æ¾ç¤ºæµè§å¨çé¢22 slowMo: 200, //åéæ¾ç¤ºï¼ææ¶ä¼ä½ä¸ºæ¨¡æ人æä½ç¹æåé23 devtools: true //æ¾ç¤ºå¼åè
å·¥å
·ã页é¢å®½é«é»è®¤800*600,æå¼åè
å·¥å
·æ¾ç¤ºåéè页é¢ä¼å 满å±å¹ï¼æ没æ大佬解éä¸ï¼24 });25 //çæPage对象26 const page = await browser.newPage();27 // const page = (await browser.pages())[0]; //è¿æ¯æçåæ³ï¼åªæä¸ä¸ªtab28 let data = 'è¯è¯ æç« uri è¯è¯é¢ç æç« é¿åº¦ï¼è¯è¯æ°éï¼\n';29 let count = 0;30 // BFSç¬åç½é¡µ31 while (waitForUrl.length !== 0 || (waitForUrlChild.length !== 0)) {32 // console.log(waitForUrl);33 // æä¸é¢ä¸å±çå¾
被ç¬åçurlæ¾è¿çå¾
éå34 if (waitForUrl.length == 0) {35 currdeep++;36 waitForUrl = waitForUrlChild;37 waitForUrlChild = [];38 }39 count++;40 let url = waitForUrl.shift();41 processedurl.push(url);42 try {43 await page.goto(url,{timeout: 60000});44 } catch (err) {45 console.log(err);46 }47 // æ¦æªé¡µé¢çèµæºè¯·æ±48 // await page.setRequestInterception(true);49 let docContent = '';50 let jsHandle ;51 let myvar = [];52 try {53 jsHandle = await page.evaluate(() => {54 // get content55 let content = document.body.innerText;56 // get href list57 let alist = document.getElementsByTagName("a");58 let res = [];59 alist = Array.from(alist);60 alist.forEach(e => {61 if (e.href) {62 res.push(e.href);63 }64 });65 // console.log(new Set(res));66 res = Array.from(new Set(res));67 const obj = {68 content:content,69 list:res70 }71 return Promise.resolve(obj);72 });73 } catch (err) {74 console.log(err);75 }76 // æ´æ°å¾
ç¬åæ°ç»77 if(jsHandle){78 myvar = jsHandle.list;79 myvar = myvar.filter(e => {80 return processedurl.indexOf(e) == -1 && waitForUrl.indexOf(e) == -1;81 });82 waitForUrlChild = waitForUrlChild.concat(myvar);83 }84 // æ¿å°ææ¬çå
容è¿è¡å¤ç85 docContent = jsHandle?jsHandle.content:'';86 if(docContent){87 var result = segment.doSegment(docContent, {88 stripStopword: true,89 simple: true90 });91 result = Array.from(new Set(result));92 let wordtotalCount = 0;93 // 计ç®æç« çè¯è¯æ»æ°94 result.forEach(x => {95 let num = getTF(docContent,x);96 wordtotalCount += num;97 });98 // ææ°çè®°å½å å
¥ç´¢å¼99 result.forEach(x => {100 let num = getTF(docContent,x);101 updateRefrence(x,url,num,wordtotalCount);102 data += `${x} ${url} ${num} ${wordtotalCount}\n`;103 });104 fs.writeFileSync("./index.txt",data, (err) => {105 if (err) throw err;106 console.log('It\'s saved!');107 });108 fs.writeFileSync("./db.txt",JSON.stringify(refrence), (err) => {109 if (err) throw err;110 console.log('It\'s saved!');111 });112 fs.writeFileSync("./docnum.txt",count, (err) => {113 if (err) throw err;114 console.log('It\'s saved!');115 });116 // console.log(count);117 }118 }119 await browser.close(); //å
³éæµè§å¨120})();121// ææ°çè®°å½å å
¥ç´¢å¼122function updateRefrence(word,url,wordnum,totalWord){123 if(refrence[word]){124 let obj = {125 url:url,126 tf:wordnum,127 totalWord:totalWord128 };129 let indexInfo = refrence[word];130 indexInfo.push(obj);131 refrence[word] = indexInfo;132 }else{133 refrence[word] = [{134 url:url,135 tf:wordnum,136 totalWord:totalWord137 }]138 }139}140// è·åè¯è¯åºç°çé¢ç141function getTF(context,word){ 142 var count=context.split(word).length-1;143 return count;...
wait.js
Source:wait.js
1/*global casper*/2/*jshint strict:false*/3casper.test.begin('wait() tests', 1, function(test) {4 var waitStart;5 casper.start('tests/site/index.html', function() {6 waitStart = new Date().getTime();7 });8 casper.wait(250, function() {9 test.assert(new Date().getTime() - waitStart > 250,10 'Casper.wait() can wait for a given amount of time');11 });12 casper.run(function() {13 test.done();14 });15});16casper.test.begin('waitFor() tests', 2, function(test) {17 casper.start('tests/site/waitFor.html');18 casper.waitFor(function() {19 return this.evaluate(function() {20 return document.querySelectorAll('li').length === 4;21 });22 }, function() {23 test.pass('Casper.waitFor() can wait for something to happen');24 }, function() {25 test.fail('Casper.waitFor() can wait for something to happen');26 });27 casper.reload().waitFor(function(){28 return false;29 }, function() {30 test.fail('waitFor() processes onTimeout callback');31 }, function() {32 test.pass('waitFor() processes onTimeout callback');33 }, 1000);34 casper.run(function() {35 test.done();36 });37});38casper.test.begin('waitForResource() tests', 2, function(test) {39 casper.start('tests/site/waitFor.html');40 casper.waitForResource('phantom.png', function() {41 test.pass('Casper.waitForResource() waits for a resource');42 }, function() {43 test.fail('Casper.waitForResource() waits for a resource');44 });45 casper.reload().waitForResource(/phantom\.png$/, function() {46 test.pass('Casper.waitForResource() waits for a resource using RegExp');47 }, function() {48 test.fail('Casper.waitForResource() waits for a resource using RegExp');49 });50 casper.run(function() {51 test.done();52 });53});54casper.test.begin('waitForSelector() tests', 1, function(test) {55 casper.start('tests/site/waitFor.html');56 casper.waitForSelector('li:nth-child(4)', function() {57 test.pass('Casper.waitForSelector() waits for a selector to exist');58 }, function() {59 test.fail('Casper.waitForSelector() waits for a selector to exist');60 });61 casper.run(function() {62 test.done();63 });64});65casper.test.begin('waitForText() tests', 3, function(test) {66 casper.start('tests/site/waitFor.html');67 casper.waitForText('<li>four</li>', function() {68 test.pass('Casper.waitForText() can wait for text');69 }, function() {70 test.fail('Casper.waitForText() can wait for text');71 });72 casper.reload().waitForText(/four/i, function() {73 test.pass('Casper.waitForText() can wait for regexp');74 }, function() {75 test.fail('Casper.waitForText() can wait for regexp');76 });77 casper.reload().waitForText('Voilà ', function() {78 test.pass('Casper.waitForText() can wait for decoded HTML text');79 }, function() {80 test.fail('Casper.waitForText() can wait for decoded HTML text');81 }, 1000);82 casper.run(function() {83 test.done();84 });85});86casper.test.begin('waitForSelectorTextChange() tests', 1, function(test) {87 casper.start('tests/site/waitFor.html');88 casper.waitForSelectorTextChange('#textChange', function() {89 test.pass('Casper.waitForSelectorTextChange() can wait for text on a selector to change');90 }, function() {91 test.fail('Casper.waitForSelectorTextChange() can wait for text on a selector to change');92 });93 casper.run(function() {94 test.done();95 });96});97casper.test.begin('waitUntilVisible() tests', 2, function(test) {98 casper.start('tests/site/waitFor.html');99 casper.waitUntilVisible('li:nth-child(4)', function() {100 test.pass('Casper.waitUntilVisible() waits for a selector being visible');101 }, function() {102 test.fail('Casper.waitUntilVisible() waits for a selector being visible');103 });104 casper.waitUntilVisible('p', function() {105 test.pass('Casper.waitUntilVisible() waits for a selector being visible');106 }, function() {107 test.fail('Casper.waitUntilVisible() waits for a selector being visible');108 });109 casper.run(function() {110 test.done();111 });112});113casper.test.begin('waitForUrl() regexp tests', 1, function(test) {114 casper.start().thenEvaluate(function() {115 setTimeout(function() {116 document.location = './form.html';117 }, 100);118 });119 casper.waitForUrl(/form\.html$/, function() {120 test.pass('Casper.waitForUrl() waits for a given regexp url');121 });122 casper.run(function() {123 test.done();124 });125});126casper.test.begin('waitForUrl() string tests', 1, function(test) {127 casper.start().thenEvaluate(function() {128 setTimeout(function() {129 document.location = './form.html';130 }, 100);131 });132 casper.waitForUrl('form.html', function() {133 test.pass('Casper.waitForUrl() waits for a given string url');134 });135 casper.run(function() {136 test.done();137 });...
login.spec.js
Source:login.spec.js
1/* eslint-disable */2// NOTE Atte Keinänen 9/8/17: This can't be converted to Jest as NodeJS doesn't have cookie support3// Probably we just want to remove this test.4import { By } from "selenium-webdriver";5import {6 waitForUrl,7 screenshot,8 loginMetabase,9 describeE2E,10} from "../support/utils";11import { METABASE_SESSION_COOKIE } from "metabase/lib/cookies";12jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;13describeE2E("auth/login", () => {14 let sessionId;15 describe("has no cookie", () => {16 beforeEach(async () => {17 await driver.get(`${server.host}/`);18 await driver.manage().deleteAllCookies();19 });20 it("should take you to the login page", async () => {21 await driver.get(`${server.host}/`);22 await waitForUrl(driver, `${server.host}/auth/login?redirect=%2F`);23 expect(await driver.isElementPresent(By.css("[name=email]"))).toEqual(24 true,25 );26 await screenshot(driver, "screenshots/auth-login.png");27 });28 it("should log you in", async () => {29 await driver.get(`${server.host}/`);30 await loginMetabase(driver, "bob@metabase.com", "12341234");31 await waitForUrl(driver, `${server.host}/`);32 const sessionCookie = await driver33 .manage()34 .getCookie(METABASE_SESSION_COOKIE);35 sessionId = sessionCookie.value;36 });37 it("should redirect you after logging in", async () => {38 await driver.get(`${server.host}/questions`);39 await waitForUrl(40 driver,41 `${server.host}/auth/login?redirect=%2Fquestions`,42 );43 await loginMetabase(driver, "bob@metabase.com", "12341234");44 await waitForUrl(driver, `${server.host}/questions`);45 });46 });47 describe("valid session cookie", () => {48 beforeEach(async () => {49 await driver.get(`${server.host}/`);50 await driver.manage().deleteAllCookies();51 await driver.manage().addCookie(METABASE_SESSION_COOKIE, sessionId);52 });53 it("is logged in", async () => {54 await driver.get(`${server.host}/`);55 await waitForUrl(driver, `${server.host}/`);56 await screenshot(driver, "screenshots/loggedin.png");57 });58 it("loads the qb", async () => {59 await driver.get(60 `${61 server.host62 }/question#eyJuYW1lIjpudWxsLCJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJ0eXBlIjoibmF0aXZlIiwibmF0aXZlIjp7InF1ZXJ5Ijoic2VsZWN0ICdvaCBoYWkgZ3Vpc2Ug8J-QsScifSwicGFyYW1ldGVycyI6W119LCJkaXNwbGF5Ijoic2NhbGFyIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e319`,63 );64 await waitForUrl(65 driver,66 `${67 server.host68 }/question#eyJuYW1lIjpudWxsLCJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJ0eXBlIjoibmF0aXZlIiwibmF0aXZlIjp7InF1ZXJ5Ijoic2VsZWN0ICdvaCBoYWkgZ3Vpc2Ug8J-QsScifSwicGFyYW1ldGVycyI6W119LCJkaXNwbGF5Ijoic2NhbGFyIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e319`,69 );70 await screenshot(driver, "screenshots/qb.png");71 });72 });...
browser_urlbar_canonize_on_autofill.js
Source:browser_urlbar_canonize_on_autofill.js
1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3/* This test ensures that pressing ctrl+enter bypasses the autoFilled4 * value, and only considers what the user typed (but not just enter).5 */6async function test_autocomplete(data) {7 let {desc, typed, autofilled, modified, waitForUrl, keys} = data;8 info(desc);9 await promiseAutocompleteResultPopup(typed);10 is(gURLBar.textValue, autofilled, "autofilled value is as expected");11 let promiseLoad = waitForDocLoadAndStopIt(waitForUrl);12 keys.forEach(([key, mods]) => EventUtils.synthesizeKey(key, mods));13 is(gURLBar.textValue, modified, "value is as expected");14 await promiseLoad;15 gURLBar.blur();16}17add_task(async function() {18 registerCleanupFunction(async function() {19 Services.prefs.clearUserPref("browser.urlbar.autoFill");20 gURLBar.handleRevert();21 await PlacesUtils.history.clear();22 });23 Services.prefs.setBoolPref("browser.urlbar.autoFill", true);24 // Add a typed visit, so it will be autofilled.25 await PlacesTestUtils.addVisits({26 uri: "http://example.com/",27 transition: Ci.nsINavHistoryService.TRANSITION_TYPED,28 });29 await test_autocomplete({ desc: "CTRL+ENTER on the autofilled part should use autofill",30 typed: "exam",31 autofilled: "example.com/",32 modified: "example.com",33 waitForUrl: "http://example.com/",34 keys: [["KEY_Enter"]],35 });36 await test_autocomplete({ desc: "CTRL+ENTER on the autofilled part should bypass autofill",37 typed: "exam",38 autofilled: "example.com/",39 modified: "www.exam.com",40 waitForUrl: "http://www.exam.com/",41 keys: [["KEY_Enter", {ctrlKey: true}]],42 });...
browser_autoFill_canonize.js
Source:browser_autoFill_canonize.js
1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3/* This test ensures that pressing ctrl+enter bypasses the autoFilled4 * value, and only considers what the user typed (but not just enter).5 */6async function test_autocomplete(data) {7 let { desc, typed, autofilled, modified, waitForUrl, keys } = data;8 info(desc);9 await promiseAutocompleteResultPopup(typed);10 Assert.equal(11 gURLBar.textValue,12 autofilled,13 "autofilled value is as expected"14 );15 let promiseLoad = BrowserTestUtils.waitForDocLoadAndStopIt(16 waitForUrl,17 gBrowser.selectedBrowser18 );19 keys.forEach(([key, mods]) => EventUtils.synthesizeKey(key, mods));20 Assert.equal(gURLBar.textValue, modified, "value is as expected");21 await promiseLoad;22 gURLBar.blur();23}24add_task(async function() {25 registerCleanupFunction(async function() {26 Services.prefs.clearUserPref("browser.urlbar.autoFill");27 gURLBar.handleRevert();28 await PlacesUtils.history.clear();29 });30 Services.prefs.setBoolPref("browser.urlbar.autoFill", true);31 // Add a typed visit, so it will be autofilled.32 await PlacesTestUtils.addVisits({33 uri: "http://example.com/",34 transition: Ci.nsINavHistoryService.TRANSITION_TYPED,35 });36 await test_autocomplete({37 desc: "CTRL+ENTER on the autofilled part should use autofill",38 typed: "exam",39 autofilled: "example.com/",40 modified: "example.com",41 waitForUrl: "http://example.com/",42 keys: [["KEY_Enter"]],43 });44 await test_autocomplete({45 desc: "CTRL+ENTER on the autofilled part should bypass autofill",46 typed: "exam",47 autofilled: "example.com/",48 modified: "www.exam.com",49 waitForUrl: "http://www.exam.com/",50 keys: [["KEY_Enter", { ctrlKey: true }]],51 });...
authProtectedRedirects.spec.js
Source:authProtectedRedirects.spec.js
...4 async () => {5 test('index redirects to login if user not authenticated', 6 async ({ page }) => {7 await page.goto('/')8 await page.waitForURL('/login')9 await expect(page.locator('#full-login-submit-button')).toBeVisible()10 })11 test('account settings redirects to login if user not authenticated',12 async ({ page }) => {13 await page.goto('/settings/account')14 await page.waitForURL('/login')15 await expect(page.locator('#full-login-submit-button')).toBeVisible()16 })17 test('notifications settings redirects to login if user not authenticated',18 async ({ page }) => {19 await page.goto('/settings/notifications')20 await page.waitForURL('/login')21 await expect(page.locator('#full-login-submit-button')).toBeVisible()22 })23 test('login redirects to index if user is authenticated',24 async ({ page }) => {25 await login(page, TESTUSER_REGISTERED)26 27 await page.goto('/login');28 await page.waitForURL('/');29 await expect(page.locator('h3:has-text("dashboard")')).toBeVisible()30 })31 // test discussion page redirects to login if user not authenticated...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await browser.close();7})();8const playwright = require('playwright');9(async () => {10 const browser = await playwright.chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 await browser.close();14})();15const playwright = require('playwright');16(async () => {17 const browser = await playwright.chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 await browser.close();21})();22const playwright = require('playwright');23(async () => {24 const browser = await playwright.chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await browser.close();28})();29const playwright = require('playwright');30(async () => {31 const browser = await playwright.chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await browser.close();35})();36const playwright = require('playwright');37(async () => {38 const browser = await playwright.chromium.launch();39 const context = await browser.newContext();40 const page = await context.newPage();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForURL(/google\.com/);7 await page.waitForURL(/google\.com/, { timeout: 1000 });8 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'attached' });9 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'detached' });10 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'visible' });11 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'hidden' });12 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'stable' });13 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'complete' });14 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'domcontentloaded' });15 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'networkidle' });16 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'load' });17 await page.waitForURL(/google\.com/, { timeout: 1000, waitUntil: 'load' });18 await browser.close();19})();20const playwright = require('playwright');21(async () => {22 const browser = await playwright.webkit.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.waitForURL(/google\.com/);26 await page.waitForURL(/google\.com/, { timeout: 1000 });27 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'attached' });28 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'detached' });29 await page.waitForURL(/google\.com/, { timeout: 1000, state: 'visible' });30 await page.waitForURL(/google\.com/, {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 await page.waitForNavigation();14 await browser.close();15})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await browser.close();6})();7module.exports = {8 use: {9 viewport: { width: 1280, height: 720 },10 waitForURL: async (page, url) => {11 await page.waitForURL(url);12 },13 },14};15const playwright = require('playwright');16(async () => {17 const browser = await playwright.chromium.launch();18 const page = await browser.newPage();19 await browser.close();20})();21module.exports = {22 use: {23 viewport: { width: 1280, height: 720 },24 waitForURL: async (page, url) => {25 await page.waitForURL(url);26 },27 },28 {29 use: {30 },31 },32 {33 use: {34 },35 },36 {37 use: {38 },39 },40};41const playwright = require('playwright');42(async () => {43 for (const browserType of ['chromium', 'firefox', 'webkit']) {44 const browser = await playwright[browserType].launch();45 const page = await browser.newPage();46 await browser.close();47 }48})();
Using AI Code Generation
1const playwright = require("playwright");2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await browser.close();7})();8Is there any way to wait for a specific URL to load in the browser without using waitForURL() ?9You can use the following code to import the waitForURL method from the Playwright internal API:10const { waitForURL } = require('playwright/lib/internal/frames');11You can use the following code to import the waitForURL method from the Playwright internal API:12const { waitForURL } = require('playwright/lib/internal/frames');
Using AI Code Generation
1const { waitForURL } = require('playwright/lib/internal');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await waitForURL(page, /\/docs/);8 console.log('URL matched!');9 await browser.close();10})();11The waitForURL method is available in the playwright package. To use it, you need to import it from the playwright/lib/internal module. It’s not available in the Playwright package. It’s not available in the Playwright API documentation. It’s not part of the Playwright API. It’s not recommended to use it in your tests because it can be changed or removed in the
Using AI Code Generation
1const { waitForURL } = require('@playwright/test/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await Promise.all([8 page.click('text=Docs'),9 ]);10 await browser.close();11})();12const { URL } = require('url');13module.exports.waitForURL = async (page, url, timeout = 30000) => {14 const parsedURL = new URL(url);15 const urlPattern = parsedURL.origin + parsedURL.pathname;16 const urlRegex = new RegExp(urlPattern.replace(/\*/g, '.*'));17 const error = await page.waitForEvent('pageerror', { timeout });18 if (error.message.match(urlRegex))19 return;20 throw error;21};
Using AI Code Generation
1const { waitForURL } = require('playwright/lib/server/network');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const [response] = await Promise.all([7 page.waitForResponse('**/api/v1/launches/latest'),8 ]);9 console.log(response.url());10 await browser.close();11})();12export const waitForURL = async (url, options) => {13 const { timeout = 30000 } = options;14 const { page } = getTestState();15 const urlRegex = new RegExp(url);16 const response = await page.waitForResponse(urlRegex, { timeout });17 return response;18};19export const waitForURL = async (url, options) => {20 const { timeout = 30000 } = options;21 const { page } = getTestState();22 const urlRegex = new RegExp(url);23 const response = await page.waitForResponse(urlRegex, { timeout });24 return response;25};26export const waitForURL = async (url, options) => {27 const { timeout = 30000 } = options;28 const { page } = getTestState();29 const urlRegex = new RegExp(url);30 const response = await page.waitForResponse(urlRegex, { timeout });31 return response;32};33export const waitForURL = async (url, options) => {34 const { timeout = 30000 } = options;35 const { page } = getTestState();36 const urlRegex = new RegExp(url);37 const response = await page.waitForResponse(urlRegex, { timeout });38 return response;39};40export const waitForURL = async (url, options) => {41 const { timeout = 30000 } = options;42 const { page } = getTestState();
Using AI Code Generation
1const { waitForURL } = require(‘playwright/lib/internal/helper’);2const { chromium } = require(‘playwright’);3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await waitForURL(page, ‘google.com’);8 await waitForURL(page, /google/);9 await browser.close();10})();11const { waitForURL } = require(‘playwright/lib/internal/helper’);12const { chromium } = require(‘playwright’);13describe(‘Test’, () => {14 let browser;15 let context;16 let page;17 beforeAll(async () => {18 browser = await chromium.launch();19 context = await browser.newContext();20 page = await context.newPage();21 });22 afterAll(async () => {23 await browser.close();24 });25 it(‘Test’, async () => {26 await waitForURL(page, ‘google.com’);27 await waitForURL(page, /google/);28 });29});
Using AI Code Generation
1const { chromium } = require('playwright');2const { waitForURL } = require('playwright/internal');3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6await page.screenshot({ path: 'google.png' });7await browser.close();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!