Selenium request returns error 400 - Bad request - selenium

I'm trying to get pull data from http://43.248.49.97/indexEn
Normally on the browser there is a first request to the url above returns error 412, the second one is to a JS file and the third one is also to the url above and returns ok (200).
When using selenium the third request returns error 400 - Bad request instead.
I'm using Python. Any ideas on why this is happening?]
Thanks

I had the same problem with you but I found a solution which perfectly solves my problem.
Maybe your program fails because you are detected as a robot using selenium.
So here is the method to solve it or hide your identity(window.navigator.webdriver) by using JavaScript:
With CDP(Chrome Devtools-Protocol), you run the code before the frame is loaded by the JS file(detector). Therefore, use these codes to remove the "webdriver True" property:
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
key codes:
from selenium.webdriver import Chrome
driver = Chrome('D://chromedriver.exe')
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})
driver.get('http://pythonlearner.com')
However, if you upgrade your Chrome to 88 right now. The method mentioned above will be useless. Fortunately, we still have a solution (add this code)
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
These codes should help you pass the JS file so that you can obtain the data. At least I successfully run my program.

I am using ChromeDriver 104.0.5112.79.0 and the solution with chrome_options.add_argument("--disable-blink-features=AutomationControlled") works for me!

Related

Leadfoot + sauce: mapping a collection of elements using getAttr fails in mobile only

My use case varies for this, but in general i'm trying to collect a bunch of elements and then apply _.map() to each. The problem is that this series of .getAttribute() calls can cause a test that works locally to fail against a remote server like sauce/android.
One example: collecting all <div class='article'><a href='articles/{id}'> on a page and then getting the hrefs. it might look something like this, and this approach will work until i test on a mobile (android) sauce environment. then I get a timeout.
Is it possible this is an issue related to my android environment capabilities? To piling up so many requests? I've tried scaling my test down from using 75 articles to only 45 and i've upped the timeout to 60s and still the mobile test fails. locally with chromedriver is fine, chrome desktop + sauce is fine.
Not my actual test but an approximation of the code i'm talking about:
/// ... return this.remote
.findAllByTagName('div.article a')
.then(function (articles) {
var promises = articles.map(function(article) {
return article.getAttribute('href');
});
Promise.all(promises)
.then(function (hrefs) {
uniques = _.uniq(hrefs);
assert(hrefs.length === uniques.length);
});
});
Since you're seeing a timeout error, I'd suggest continuing to increase the test timeout until the test passes. The mobile testing environments on Sauce are both slower to initialize and slower to operate than the desktop environments, so it's quite possible that a test with many requests is simply very slow.
One way to speed things up would be to use an execute block to gather the references, like:
.then(function (articles) {
return this.parent.execute(function (articles) {
return articles.map(function (node) {
return node.getAttribute('href');
});
}, [ articles ]);
})
In the above snippet, the articles element array is passed as an argument to the execute block. The remote WebDriver will deserialize the element references into actual DOM elements that can be operated on in the execute code. This is significantly more efficient than using individual getAttribute requests for each element since only a single request will be made to the remote browser.

Access window object / browser scope from protractor

I'm running tests with protractor, but it seems impossible to access the JS 'window' object. I even tried adding a tag in my html file that would contain something like
var a = window.location;
and then try expect(a) but I couldn't make it work, I always get undefined references...
How should I process to access variables that are in the browser scope ?
Assuming you are using a recent version of Protractor, let's say >= 1.1.0, hopefully >= 1.3.1
Attempting to access Browser side JS code directly from Protractor won't work because Protractor runs in NodeJS and every Browser side code is executed through Selenium JsonWireProtocol.
Without further detail, a working example:
browser.get('https://angularjs.org/');
One-liner promise that, as of today, resolves to '1.3.0-rc.3'
browser.executeScript('return window.angular.version.full;');
You can use it directly in an expect statement given Protractor's expect resolves promises for you:
expect(browser.executeScript('return window.angular.version.full;')).
toEqual('1.3.0-rc.3');
Longer example passing a function instead of a string plus without expect resolving the promise for you. i.e. for more control and for doing some fancy thing with the result.
browser.driver.executeScript(function() {
return window.angular.version.full;
}).then(function(result) {
console.log('NodeJS-side console log result: ' + result);
//=> NodeJS-side console log result: 1.3.0-rc.3
});

Is it possible to use dojo/text! in an Intern functional test?

Is it possible to use "dojo/text!" in an Intern functional test?
I am able to setup my test page as a JSON string, but ideally I'd like to externalise the string in a file for ease of editing. I'm just getting started with Intern at the moment so I'm just experimenting with what's possible, but here is the start of my test code).
This works with the commented "testData" variable used, but is currently failing when I try to provide the same String by the dojo/text! statement.
Code:
define([
'intern!object',
'intern/chai!assert',
'dojo/text!./firstTestPageConfig.json',
'require'
], function (registerSuite, assert, PageConfig, require) {
registerSuite({
name: 'firstTest',
'greeting form': function () {
var testData = PageConfig;
// var testData = '{"widgets":[{"name":"alfresco/menus/AlfMenuBar","config":{"widgets":[{"name":"alfresco/menus/AlfMenuBarPopup","config":{"id":"DD1","label":"Drop-Down","iconClass":"alf-configure-icon","widgets":[{"name":"alfresco/menus/AlfMenuGroup","config":{"label":"Group 1","widgets":[{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 1","iconClass":"alf-user-icon"}},{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 2","iconClass":"alf-password-icon"}}]}},{"name":"alfresco/menus/AlfMenuGroup","config":{"label":"Group 2","widgets":[{"name":"alfresco/menus/AlfMenuItem","config":{"label":"Item 3","iconClass":"alf-help-icon"}}]}}]}}]}}]}';
var testPage = 'http://localhost:8081/share/page/tp/ws/unittest?testdata=';
return this.remote
.get(testPage + testData)
.waitForElementByCssSelector('.alfresco-core-Page.allWidgetsProcessed', 5000)
.elementById('DD1')
.clickElement()
.end()
}
});
});
The error I'm getting is this:
/home/dave/ScratchPad/ShareInternTests/node_modules/intern/node_modules/dojo/dojo.js:742
throw new Error('Failed to load module ' + module.mid + ' from ' + url +
^
Error: Failed to load module dojo/text from /home/dave/ScratchPad/ShareInternTests/dojo/text.js (parent: dojo/text!17!*)
at /home/dave/ScratchPad/ShareInternTests/node_modules/intern/node_modules/dojo/dojo.js:742:12
at fs.js:207:20
at Object.oncomplete (fs.js:107:15)
I've tried playing around with the loader/package/map configuration but without any success. It's not clear (to me at least) from the error message whether or not it can't find the file I'm passing to dojo/text (but I've tried full as well as relative paths) or the Dojo module itself ?
I'd just like to confirm that what I'm attempting is possible, before I spend any more time with this... but obviously any solution or example would be greatly appreciated!!
Many thanks,
Dave
To your specific error: You need to install Dojo for your own project if you want to use it. You are trying to load a module that does not exist. You may also try using the copy that comes with Intern, by loading modules from intern/dojo, but this isn’t recommended if you don’t understand the potential caveats of loading this internal library.
To using dojo/text in a functional test, generally: This is not currently possible unless you use the Geezer branch or explicitly use the Dojo 1 loader, because that module relies on functionality that is only exposed by the Dojo 1 loader when running in Node.js. A different text loader module that is fully generic would work, or you could load intern/dojo/node!fs and load the text yourself. This will be addressed in the future.
I just came across the same issue and for me this worked:
define([
"dojo/_base/declare",
"intern/dojo/text!/[PathToText]"
], function (declare, base) {
Seems as if Sitepen has included this in the meantime...

Testing Backbone Model with Jasmine and Sinon - Object #<Object> has no method 'spy'

I am trying to learn how to use Jasmine and Sinon for testing a Backbone application, and I was following this tutorial. Nevertheless, I ran into a problem that I don't know how to solve.
Most likely the solution is simple, but I need some guidance ...
In my project.spec.js file this is the code that is giving the problem:
it("should not save when name is empty", function() {
var eventSpy = sinon.spy();
this.project.bind("error", eventSpy);
this.project.save({"name": ""});
expect(this.eventSpy.calledOnce).toBeTruthy();
expect(this.eventSpy.calledWith(
this.project,
"cannot have an empty name"
)).toBeTruthy();
});
And this is the specific error that can be seen in the browser:
Failing 1 spec
7 specs | 1 failing
Project model should not save when name is empty.
TypeError: Object #<Object> has no method 'spy'
TypeError: Object #<Object> has no method 'spy'
at null.<anonymous> (http://localhost:8888/__spec__/models/project.spec.js:53:26)
at jasmine.Block.execute (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:1024:15)
at jasmine.Queue.next_ (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2025:31)
at jasmine.Queue.start (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:1978:8)
at jasmine.Spec.execute (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2305:14)
at jasmine.Queue.next_ (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2025:31)
at onComplete (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2021:18)
at jasmine.Suite.finish (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2407:5)
at null.onComplete (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2451:10)
at jasmine.Queue.next_ (http://localhost:8888/__JASMINE_ROOT__/jasmine.js:2035:14)
In addition to the sinon.js library, I have installed the jasmine-sinon.js library (both are in the vendor/assets/javascripts folder and are included in the application.js file).
Thank you,
Alexandra
I faced this problem when I downloaded sinon.js file from GitHub (without Sinon folder). I solved the problem by downloading the library from http://sinonjs.org/
I'm going to post this as an answer, based on the comment thread above. We've narrowed down the problem to the line where sinon.spy() is called, so it's not specific to this test but to how sinon is being loaded.
I suspect the problem is that you're including sinon and jasmine-sinon in application.js, when they should really go in spec/javascripts/spec.js (in the same format). Try changing that and see if anything changes.
UPDATE:
Based on the comment thread below, it seems the code is getting to the this.project.save(...) line but the validations aren't working: I know this because if you're getting a POST error in the console, it means that backbone actually made the request (which it should not have because the name is empty). So you should go back and check the code you are actually testing.
I know this thread is old, but I had a similar issue today with this when going through this tutorial http://tinnedfruit.com/2011/03/25/testing-backbone-apps-with-jasmine-sinon-2.html. It looks like Backbone made a change and it calls the 'invalid' event when invalid model data is provided, not 'error'.
If you run into this error try changing:
it("should not save when name is empty", function() {
...
this.project.bind("error", eventSpy);
...
});
To:
it("should not save when name is empty", function() {
...
this.project.bind("invalid", eventSpy);
...
});
This resolved the issue for me.

Selenium IDE: this.browserbot.getUserWindow().typeList.filter returns error on IE8

I have faced with following trouble during working with Selenium.
I need to verify that some value exists in list and I use the following code:
assertEval
this.browserbot.getUserWindow().typeList.filter(function(v) { return v[0] === 'Type_${r_suffix}'; })[0][0];
Type_${r_suffix}
This works file on Firefox, but on IE 8 returns error: Object doesn't support this property or method.
Could someone have an idea where is a problem?
As the MDN docs say, the filter() method is available only for IE9 and above.
Your're just using a too new technology. Filter it manually using a for loop or insert the code for Array.prototype.filter (from the MDN) to have access to it.