本文将带您了解关于量角器在PhantomJS上运行测试的新内容,同时我们还将为您解释量角器protractor的相关知识,另外,我们还将为您提供关于16、web爬虫讲解2—PhantomJS虚拟浏览器
本文将带您了解关于量角器在PhantomJS上运行测试的新内容,同时我们还将为您解释量角器protractor的相关知识,另外,我们还将为您提供关于16、web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS、Angular 2测试:使用PhantomJS进行测试时“无法找到变量:标题”,但与Chrome一起正常工作、angularjs – 具有打字稿的量角器在成功解决后无法找到模块’量角器’、angularjs – 在Browserstack自动化上运行量角器测试的实用信息。
本文目录一览:- 量角器在PhantomJS上运行测试(量角器protractor)
- 16、web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS
- Angular 2测试:使用PhantomJS进行测试时“无法找到变量:标题”,但与Chrome一起正常工作
- angularjs – 具有打字稿的量角器在成功解决后无法找到模块’量角器’
- angularjs – 在Browserstack自动化上运行量角器测试
量角器在PhantomJS上运行测试(量角器protractor)
我似乎无法通过测试成功获得PhantomJS。我试图将其集成到我的项目中,但是在此之后失败了,我尝试仅运行基本的Angular
Docs示例,但遇到了同样的问题。到目前为止,我的步骤:
npm install -g phantomjs
phantomjs --webdriver=9515
// … GhostDriver-Main-在端口9515上运行protractor protractorConf.js
这是与示例中相同的文件,仅具有browserName,并且seleniumAddress端口已更改:
// An example configuration file.exports.config = { // The address of a running selenium server. seleniumAddress: ''http://localhost:9515'', // Capabilities to be passed to the webdriver instance. capabilities: { ''browserName'': ''phantomjs'' }, // Spec patterns are relative to the current working directly when // protractor is called. specs: [''onProtractorRunner.js''], // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, }};
我收到以下错误消息:
UnknownError: Error Message => ''Detected a page unload event; asynchronous script execution does not work across page loads.''
我在github上发现了这个问题,这似乎是相关的。我以为我对他们的brower-
setup.md足够了解,可以将其包含在我的beforeEach
功能之一中。然后我发现这里ptor
无论如何只是包装驱动程序。哇,我知道我在量角器/selenium土地上是个菜鸟,但是信噪比令人信服。我真的很想使用PhantomJS来获得性能上的好处,但是在此上浪费更多时间的前景正伤着我的头。如果有问题,我使用的是Windows
7 Enterprise 64位。谢谢!
答案1
小编典典从根本上来说,此修复为我解决了相同的问题:
https://github.com/pschwartau/protractor/commit/1eeff8b1b2e3e8f3b7c8152264411f26d4665a07
如此处最初所述:renanmartins的https://github.com/angular/protractor/issues/85#issuecomment-26846255
内部protractor / lib / protractor.js替换
this.driver.get(''about:blank'');this.driver.executeScript( ''window.name = "'' + DEFER_LABEL + ''" + window.name;'' + ''window.location.href = "'' + destination + ''"'');
与
var driver = this.driver; this.getCapabilities().then(function (capabilities) { if (capabilities.caps_.browserName === ''phantomjs'') { driver.executeScript(''window.name = "'' + DEFER_LABEL + ''" + window.name;''); driver.get(destination); } else { driver.get(''about:blank''); driver.executeScript( ''window.name = "'' + DEFER_LABEL + ''" + window.name;'' + ''window.location.href = "'' + destination + ''"''); } // Make sure the page is an Angular page. driver.executeAsyncScript(clientSideScripts.testForAngular, 10). then(function(hasAngular) { if (!hasAngular) { throw new Error(''Angular could not be found on the page '' + destination); } }); });
16、web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS
【百度云搜索,搜各种资料:http://www.bdyss.cn】
【搜网盘,搜各种资料:http://www.swpan.cn】
PhantomJS虚拟浏览器
phantomjs 是一个基于js的webkit内核无头浏览器 也就是没有显示界面的浏览器,利用这个软件,可以获取到网址js加载的任何信息,也就是可以获取浏览器异步加载的信息
下载网址:http://phantomjs.org/download... 下载对应系统版本
下载后解压PhantomJS文件,将解压文件夹,剪切到python安装文件夹
然后将PhantomJS文件夹里的bin文件夹添加系统环境变量
cdm 输入命令:PhantomJS 出现以下信息说明安装成功
selenium模块是一个python操作PhantomJS软件的一个模块
selenium模块PhantomJS软件
webdriver.PhantomJS()实例化PhantomJS浏览器对象
get(''url'')访问网站
find_element_by_xpath(''xpath表达式'')通过xpath表达式找对应元素
clear()清空输入框里的内容
send_keys(''内容'')将内容写入输入框
click()点击事件
get_screenshot_as_file(''截图保存路径名称'')将网页截图,保存到此目录
page_source获取网页htnl源码
quit()关闭PhantomJS浏览器
#!/usr/bin/env python
# -*- coding:utf8 -*-
from selenium import webdriver #导入selenium模块来操作PhantomJS
import os
import time
import re
llqdx = webdriver.PhantomJS() #实例化PhantomJS浏览器对象
llqdx.get("https://www.baidu.com/") #访问网址
# time.sleep(3) #等待3秒
# llqdx.get_screenshot_as_file(''H:/py/17/img/123.jpg'') #将网页截图保存到此目录
#模拟用户操作
llqdx.find_element_by_xpath(''//*[@id="kw"]'').clear() #通过xpath表达式找到输入框,clear()清空输入框里的内容
llqdx.find_element_by_xpath(''//*[@id="kw"]'').send_keys(''叫卖录音网'') #通过xpath表达式找到输入框,send_keys()将内容写入输入框
llqdx.find_element_by_xpath(''//*[@id="su"]'').click() #通过xpath表达式找到搜索按钮,click()点击事件
time.sleep(3) #等待3秒
llqdx.get_screenshot_as_file(''H:/py/17/img/123.jpg'') #将网页截图,保存到此目录
neir = llqdx.page_source #获取网页内容
print(neir)
llqdx.quit() #关闭浏览器
pat = "<title>(.*?)</title>"
title = re.compile(pat).findall(neir) #正则匹配网页标题
print(title)
PhantomJS浏览器伪装,和滚动滚动条加载数据
有些网站是动态加载数据的,需要滚动条滚动加载数据
实现代码
DesiredCapabilities 伪装浏览器对象
execute_script()执行js代码
current_url获取当前的url
#!/usr/bin/env python
# -*- coding:utf8 -*-
from selenium import webdriver #导入selenium模块来操作PhantomJS
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities #导入浏览器伪装模块
import os
import time
import re
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap[''phantomjs.page.settings.userAgent''] = (''Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'')
print(dcap)
llqdx = webdriver.PhantomJS(desired_capabilities=dcap) #实例化PhantomJS浏览器对象
llqdx.get("https://www.jd.com/") #访问网址
#模拟用户操作
for j in range(20):
js3 = ''window.scrollTo(''+str(j*1280)+'',''+str((j+1)*1280)+'')''
llqdx.execute_script(js3) #执行js语言滚动滚动条
time.sleep(1)
llqdx.get_screenshot_as_file(''H:/py/17/img/123.jpg'') #将网页截图,保存到此目录
url = llqdx.current_url
print(url)
neir = llqdx.page_source #获取网页内容
print(neir)
llqdx.quit() #关闭浏览器
pat = "<title>(.*?)</title>"
title = re.compile(pat).findall(neir) #正则匹配网页标题
print(title)
【转载自:http://www.lqkweb.com】
Angular 2测试:使用PhantomJS进行测试时“无法找到变量:标题”,但与Chrome一起正常工作
PhantomJS 2.1.1 (Mac OS X 0.0.0) UserDataService should be created Failed ReferenceError: Can't find variable: Headers in http://localhost:9876/_karma_webpack_/main.bundle.js (line 693)
这是我的user-data.service.ts文件的样子:
import {Injectable} from @angular/core"; import {Http} from "@angular/http"; import "rxjs/add/operator/map"; import "rxjs/add/operator/catch"; import "rxjs/add/operator/toPromise"; import "rxjs/add/operator/find"; import {User} from "../data-objects/user"; import {Observable} from "rxjs/Observable"; @Injectable() export class UserDataService { private userDataUrl = `api/userData`; private headers = new Headers({"Content-Type": "application/json"}); constructor(private http: Http) { } getUser(id:number): Observable<User> { const url = `${this.userDataUrl}/?id=${id}`; return this.http.get(url,this.headers) .map(response => { return response.json().data as User; }) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error("An error occurred in the user data service.",error); return Promise.reject(error.json().error || "Server Error in UserDataServer") } }
我已经尝试在网上搜索解决方案,但到目前为止还没有弄清楚为什么phantomJS找不到标题但铬可以.为了完整起见,这里分别是我的karma.conf.js和user-data.service.spec.ts文件.任何帮助,将不胜感激.
karma.conf.js
module.exports = function (config) { config.set({ basePath: '',frameworks: ['jasmine','@angular/cli'],plugins: [ require('karma-jasmine'),require('karma-chrome-launcher'),require('karma-phantomjs-launcher'),require('karma-jasmine-html-reporter'),require('karma-coverage-istanbul-reporter'),require('@angular/cli/plugins/karma') ],client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser },files: [ { pattern: './src/test.ts',watched: false },{ pattern: 'node_modules/angular-in-memory-web-api/**/*.js',included: false,watched: false } ],preprocessors: { './src/test.ts': ['@angular/cli'] },mime: { 'text/x-typescript': ['ts','tsx'] },coverageIstanbulReporter: { reports: [ 'html','lcovonly' ],fixWebpackSourcePaths: true },angularCli: { config: './angular-cli.json',environment: 'dev' },reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress','coverage-istanbul'] : ['progress','kjhtml'],port: 9876,colors: true,logLevel: config.LOG_DEBUG,autoWatch: true,// browsers: ['ChromeHeadless'],browsers: ['PhantomJS'],// browsers: ['Chrome'],singleRun: false }); };
用户data.service.spec.ts:
import {Testbed,inject} from '@angular/core/testing'; import {UserDataService} from './user-data.service'; import {Http,BaseRequestOptions} from "@angular/http"; import {MockBackend} from "@angular/http/testing"; describe('UserDataService',() => { beforeEach(() => { Testbed.configureTestingModule({ providers: [UserDataService,MockBackend,BaseRequestOptions,{provide: Http}] }); }); fit('should be created',inject([UserDataService],(service: UserDataService) => { expect(service).toBeTruthy(); })); });
解决方法
angularjs – 具有打字稿的量角器在成功解决后无法找到模块’量角器’
我有以下文件结构:
node_modules protractor typescript package.json register-popup.ts
package.json的内容
{ "name": "typescriptProba","version": "1.0.0","description": "","main": "index.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1" },"keywords": [],"author": "","license": "ISC","dependencies": { "protractor": "^4.0.11","typescript": "^2.0.10" } }
register-popup.ts的内容:
import { ElementFinder,element,by } from "protractor"; export class RegisterPopup { public registerWithFacebookButton: ElementFinder = element(by.css('li.facebook a')); public registerWithGoogleButton: ElementFinder = element(by.css('li.google a')); public registerWithEmailButton: ElementFinder = element(by.css('li.email a')); public registerWithMobileButton: ElementFinder = element(by.css('li.natel a')); constructor () {} openPopup() { element(by.css('.account.user')).click(); element(by.id('openRegister')).click(); } openRegisterByEmailPopup() { this.registerWithEmailButton.click(); } openRegisterByPhonePopup() { this.registerWithMobileButton.click(); } }
为了将ts文件编译为js文件,我使用以下命令:
./node_modules/typescript/bin/tsc "./register-popup.ts" --module commonjs --noresolve --traceResolution
执行命令后,我有以下错误:
error TS2307: Cannot find module 'protractor'.
但我的模块跟踪分辨率是这样的:
======== Resolving module 'protractor' from '/Users/predraglazarevic/www/typescriptProba/register-popup.ts'. ======== Module resolution kind is not specified,using 'NodeJs'. Loading module 'protractor' from 'node_modules' folder. File '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor.ts' does not exist. File '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor.tsx' does not exist. File '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor.d.ts' does not exist. Found 'package.json' at '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/package.json'. 'package.json' has 'typings' field 'built/index.d.ts' that references '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/built/index.d.ts'. File '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/built/index.d.ts' exist - use it as a name resolution result. Resolving real path for '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/built/index.d.ts',result '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/built/index.d.ts' ======== Module name 'protractor' was successfully resolved to '/Users/predraglazarevic/www/typescriptProba/node_modules/protractor/built/index.d.ts'. ========
所以我有
Module name ‘protractor’ was successfully resolved
但仍然有错误
error TS2307: Cannot find module ‘protractor’.
为什么?
回答
当我省略–noresolve标志时,它正在工作.所以命令应该是
./node_modules/typescript/bin/tsc "./register-popup.ts" --module commonjs
解决方法
{ "compileOnSave": false,"compilerOptions": { "declaration": false,"emitDecoratorMetadata": true,"experimentalDecorators": true,"lib": [ "es2016" ],"module": "commonjs","moduleResolution": "node","outDir": "path/to/transpiled/files","sourceMap": true,"target": "es6","typeRoots": [ "node_modules/@types" ] } }
如果您有任何其他DefinitelyTyped模块,它们将被本地路径中的typeRoots目录选取:node_modules / @ types.
angularjs – 在Browserstack自动化上运行量角器测试
如何设置系统来运行这些测试?
您只需在conf.js中添加以下两个参数即可在browserstack上启动测试:
browserstackUser: '<username>' browserstackKey: '<automate-key>'
登录到您的帐户后,您可以在here找到您的用户名和自动密钥。
因此,让我们说您希望在Chrome 50 / OS X Yosemite上运行测试,您的conf.js应该如下所示:
exports.config = { specs: ['spec.js'],browserstackUser: '<username>',browserstackKey: '<automate-key>',capabilities: { browserName: 'Chrome',browser_version: '50.0',os: 'OS X',os_version: 'Yosemite' },};
如果您希望以不同的浏览器和操作系统组合并行运行测试,则可以使用以下给出的multiCapabilities:
exports.config = { specs: ['spec.js'],multiCapabilities: [ { browserName: 'Safari',browser_version: '8.0',os_version: 'Yosemite' },{ browserName: 'Firefox',browser_version: '30.0',os: 'Windows',os_version: '7' },{ browserName: 'iPhone',platform: 'MAC',device: 'iPhone 5S' } ] };
一些有用的链接:
> Code Generator – 帮助您配置在不同的各种浏览器和操作系统组合(尤其是移动设备)上进行测试的功能。
>用于量角器 – 浏览器堆栈的示例Github project – 这应该可以帮助您开始使用。
今天关于量角器在PhantomJS上运行测试和量角器protractor的分享就到这里,希望大家有所收获,若想了解更多关于16、web爬虫讲解2—PhantomJS虚拟浏览器+selenium模块操作PhantomJS、Angular 2测试:使用PhantomJS进行测试时“无法找到变量:标题”,但与Chrome一起正常工作、angularjs – 具有打字稿的量角器在成功解决后无法找到模块’量角器’、angularjs – 在Browserstack自动化上运行量角器测试等相关知识,可以在本站进行查询。
本文标签: