Using a functional java construct (Predicate) from jython - java

So, I'm attempting to use the selenium java libraries from jython (yes, I know selenium has a python interface, but for good reasons of corporate teamwork accessing the pure java libraries makes more sense if it can be done well).
I'm just trying to do the example script here: http://seleniumhq.org/docs/03_webdriver.html#introducing-the-selenium-webdriver-api-by-example
Which I've implemented with the following jython code:
from org.openqa.selenium.firefox import FirefoxDriver
from org.openqa.selenium import By
from org.openqa.selenium import WebDriver
from org.openqa.selenium import WebElement
from org.openqa.selenium.support.ui import ExpectedCondition
from org.openqa.selenium.support.ui import WebDriverWait
driver = FirefoxDriver()
driver.get('http://www.google.com')
element = driver.findElement(By.name('q'))
# The array wrapper around the string is the only weird thing I encountered
element.sendKeys(["Cheese!"])
print "Page title is: " + driver.getTitle()
class ExpectedConditionTitle(ExpectedCondition):
def apply(d):
print(type(d))
return d.title.toLowerCase().startsWith(["cheese!"])
def equals(d):
pass
print(type(driver))
WebDriverWait(driver, 10).until(ExpectedConditionTitle().apply())
print driver.getTitle()
driver.quit()
And it's puking on the ExpectedCondition bit. I can't figure out how to make a subclass for the variety desired by until. I've gotten the following errors with variations in my code:
last
Traceback (innermost last):
File "Example.py", line 24, in ?
File "Example.py", line 19, in apply
AttributeError: 'instance' object has no attribute 'title'
and
Traceback (innermost last):
File "Example.py", line 24, in ?
File "Example.py", line 19, in apply
AttributeError: getTitle
and
Traceback (innermost last):
File "Example.py", line 22, in ?
TypeError: until(): 1st arg can't be coerced to com.google.common.base.Function or com.google.common.base.Predicate
The selenium ExpectedCondition interface is basically just a front for the Guava Predicate interface.
I'm not well versed enough in python or java to figure this out. Anyone have any ideas how I might accomplish this?

Related

.sendKeys method problems in WebDriver Sampler JMeter

I'm making WebDriver Selenium scripts and trying to run them with JMeter.
I have an issue I don't understand. My code will crash at line 17 with this error in JMeter:
ERROR c.g.j.p.w.s.WebDriverSampler: Sourced file: inline evaluation of:
import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' : Error in method invocation: Method sendKeys( java.lang.String ) not found in class'org.openqa.selenium.remote.RemoteWebElement' : at Line: 17 : in file: inline evaluation of: ``import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' : .sendKeys ( "value" )
in inline evaluation of: ``import org.openqa.selenium.*; import java.time.Duration; WDS.sampleResult.samp . . . '' at line number 17
This is my code in WebDriver Sampler in JMeter:
code with .sendKeys method
What is the problem? Am I just blind?
I tried to import org.openqa.selenium.remote.RemoteWebElement directly to the script and I also tried to change syntax because I learned it was necessary to put an Array instead of a String behind .sendKeys method, but it didn't work for me.
I am using apache-jmeter-5.5 and Script Language in WebDriver Sampler is set to java.
You're just violating JMeter Best Practices, using Beanshell is not recommended since JMeter 3.1
The reason is that WebElement.sendKeys() function expects a CharSequence and you're trying to pass a String there and Beanshell interpreter doesn't like it.
Switch the language to groovy and the issue will go away. See Apache Groovy: What Is Groovy Used For? article for more information on Groovy scripting in JMeter

Did Matlab 2017a change how it imports external java classes?

I'm calling PDFBox from Matlab to figure out how many pages there are in a PDF. Everything works great with Matlba 2016b and prior. I can import the library and load a PDF without a problem:
import org.apache.pdfbox.pdmodel.PDDocument;
pdfFile = PDDocument.load(filename);
When I run the same thing in 2017a, I get the following error:
No method 'load' with matching signature found for class
'org.apache.pdfbox.pdmodel.PDDocument'.
I can change the line after the import so that the function signature matches:
jFilename = java.lang.String(filename);
pdfFile = PDDocument.load(jFilename.getBytes());
However, this causes PDFBox to have problems when I call load:
Java exception occurred:
java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1111)
at org.apache.pdfbox.pdfparser.COSParser.parseHeader(COSParser.java:1874)
at org.apache.pdfbox.pdfparser.COSParser.parsePDFHeader(COSParser.java:1853)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:242)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1093)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1071)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1053)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1038)
This error seems to occur regardless of the PDF I'm trying to load. I'm getting the same exception with PDFBox 1.8.10 and 2.0.6.
I'm left with 2 questions:
Did Matlab 2017a change how it passes strings to Java? I didn't see anything in the release notes about this.
What could be causing the PDFBox error? Matlab is still on Java 1.7 in 2017a so I wouldn't think there should be any difference in how PDFBox works.
It seems like the method you are calling is from PDDocument version 1.8.11
In the latest version, PDDocument version 2.0.2 the method signature for accepting a file name no longer exists.
Change your code to the following, and it should work.
pdfFile = PDDocument.load(java.io.File(filename));

JPype class not found, $1 with no inner class

I have these java files:
LDF1File.java
LDFFile.java <-- super class
which generate these class files:
LDF1File.class -- there is no inner class
LDF1File$1.class <-- no idea where this comes from
LDFFile.class
In my python code, I can import LDF1File$1, but not LDF1File. I get:
>>> JClass('aero.blue.bdms.ldf.stream.LDF1File')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/eric/Software/anaconda3/envs/blue3/lib/python3.5/site-packages/JPype1-0.6.1-py3.5-linux-x86_64.egg/jpype/_jclass.py", line 55, in JClass
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class aero.blue.bdms.ldf.stream.LDF1File not found
Here's the full code:
from jpype import *
startJVM(getDefaultJVMPath(), "-ea", '-Xms1024m', '-Xmx4096m', '-Djava.class.path=./jars/bdms-chunkjava-lib-1.0.9-SNAPSHOT.jar:./jars/bdms-ldfjava-lib-1.0.9-SNAPSHOT.jar')
LDF1File = JClass('aero.blue.bdms.ldf.stream.LDF1File')
shutdownJVM()
So i'm not sure why there is a class file with a dollar sign in it's name, and I'm not sure why JPype can't locate LDF1File. Just to rule some possible suggestions out, there is no dependency injection, no aspectj stuff, no spring, no guava. This is just plain java.
I had only included in my classpath the jar of the package i was working with and none of the dependencies. Having added all dependency jars to the classpath, it was able to load LDF1File.java

python selenium login error despite use of WebDriverWait

I am trying to write a script to help me track my Fitbit communities, but first I need to login to the site. Forgive me as I am a coding novice.
I am using Selenium in Python.
My code is as follows:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import re
##Loading selenium to handle java on leaderboard page
##
path_to_chromedriver = 'C:/python351/chromedriver/chromedriver.exe'
browser2 = webdriver.Chrome(executable_path = path_to_chromedriver)
##Login with selenium
##
login_url = 'https://www.fitbit.com/login'
browser2.get(login_url)
browser2.implicitly_wait(5)
email1 = browser2.find_element_by_name('email')
password1 = browser2.find_element_by_name('password')
email1.click()
email1.clear()
WebDriverWait(browser2, 10)
email1.send_keys('notrealemail#mail.com')
WebDriverWait(browser2, 20)
password1.click()
password1.clear()
WebDriverWait(browser2, 20)
password1.send_keys('madeuppass')
WebDriverWait(browser2, 20)
form1 = browser2.find_element_by_class('common-btn common-btn-submit track-Auth-Login-ClickFitbit')
form1.submit()
When I run it I keep getting the following errors and the email/password boxes do not fill in. Here is the traceback:
C:\python351>python -i slogin.py
[WARNING:..\..\..\..\flash\platform\pepper\pep_module.cpp(63)] SANDBOXED
Vector smash protection is enabled.
Traceback (most recent call last):
File "slogin.py", line 28, in <module>
email1.click()
File "C:\python351\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 74, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\python351\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 457, in _execute
return self._parent.execute(command, params)
File "C:\python351\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 233, in execute
self.error_handler.check_response(response)
File "C:\python351\lib\site-packages\selenium\webdriver\remote\errorhandler.py
", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visi
ble
(Session info: chrome=50.0.2661.94)
(Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7
c4),platform=Windows NT 6.1 SP1 x86_64)
I have been fiddling with this for hours and I can't get it to work. I see the element not visible error and it made me think I needed a delay, but then I tried to implement it (possibly poorly) and still I am getting errors. I also added the click and clear things as well as I saw those suggestions in other posts. I was able to login with RoboBrowser using the form submit, but some of the stuff I need to access later used java so it ended up being a dead end and now I've switched to Selenium and am stuck.
Try out this...
find_element_by_name is not able to find that element so you need to use xpath for it.
Loading selenium to handle java on leaderboard page
#
path_to_chromedriver = 'C:/python351/chromedriver/chromedriver.exe'
browser2 = webdriver.Chrome(executable_path = path_to_chromedriver)
Login with selenium
#
login_url = 'https://www.fitbit.com/login'
browser2.get(login_url)
browser2.implicitly_wait(5)
email1 = browser2.find_element_by_xpath(".//*[#id='loginForm']/fieldset/dl/dd[1]/input")
email1.send_keys('notrealemail#mail.com')
password1 = browser2.find_element_by_xpath(".//*[#id='loginForm']/fieldset/dl/dd[2]/input")
password1.send_keys('madeuppass')
form1 = browser2.find_element_by_class('common-btn common-btn-submit track-Auth-Login-ClickFitbit')
form1.click()
#
Do reply if you need more help.
I ran this code in Eclipse with java syntax it is working fine..
Happy Learning.. Enjoy :-)
You use WebDriverWait in a wrong way. Please refer to following line:
email = WebDriverWait(browser2, 10).until(EC.presence_of_element_located((By.ID,'email')))
This should allow to wait 10 seconds for required element before throwing an exception
You can also use try/except to catch TimeOut exception:
from selenium.common.exceptions import TimeoutException
try:
email = WebDriverWait(browser2, 10).until(EC.presence_of_element_located((By.ID,'email')))
except TimeoutException:
print('No Email input field found')

Jython missing functions in sys module

I have an python script which I need to run in my java application. I tried to execute it from jython but I have strange problem:
from sys import getdlopenflags
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name getdlopenflags
When I try to check contents of sys:
import sys
dir(sys)
the output is:
['JYTHON_DEV_JAR', 'JYTHON_JAR', 'PYTHON_CACHEDIR', 'PYTHON_CACHEDIR_SKIP', 'PYTHON_CONSOLE_ENCODING', '__delattr__', '__dict__', '__displayhook__', '__excepthook__', '__findattr_ex__', '__name__', '__new__', '__rawdir__', '__setattr__', '__stderr__', '__stdin__', '__stdout__', '_getframe', '_jy_interpreter', '_systemRestart', 'add_classdir', 'add_extdir', 'add_package', 'argv', 'builtin_module_names', 'builtins', 'byteorder', 'classDictInit', 'classLoader', 'cleanup', 'copyright', 'currentWorkingDir', 'defaultencoding', 'determinePlatform', 'displayhook', 'doInitialize', 'exc_clear', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'filesystemencoding', 'getBaseProperties', 'getBuiltin', 'getBuiltins', 'getClassLoader', 'getCurrentWorkingDir', 'getDefaultBuiltins', 'getPath', 'getPathLazy', 'getPlatform', 'getWarnoptions', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'hexversion', 'initialize', 'isPackageCacheEnabled', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 'meta_path', 'minint', 'modules', 'packageManager', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'recursionlimit', 'registerCloser', 'registry', 'setBuiltins', 'setClassLoader', 'setCurrentWorkingDir', 'setPlatform', 'setWarnoptions', 'setprofile', 'setrecursionlimit', 'settrace', 'shadow', 'stderr', 'stdin', 'stdout', 'subversion', 'toString', 'unregisterCloser', 'version', 'version_info', 'warnoptions']
obviously getdlopenflags is missing. Is it possible to use this function in jython (I have the newest - 2.5.2) According to the documentation on the http://jython.org/docs/library/sys.html the sys.getdlopenflags is present.
Thanks for help
It says "Availability: Unix" in the documentation. The Jython docs seem to have copied that unchanged from the CPython docs. So this function is only available on a Unix installation. Possibly Jython doesn't have it at all - I don't know Java well enough, but since it's supposedly platform-independent, it can't support system-specific functions.

Categories

Resources