Reputation: 13
I'm new to python and trying to convert my selenium-Java scripts into selenium-python. I've been struggling to convert below code. Well, this is running successfully with Selenium-Java.
I got stuck wherein i would like to get the attribute value at a particular location and converting it to a string.
String indx=element.getAttribute("num");
int k=Integer.parseInt(indx);
element.sendKeys(""+a[k]);
How do I get that running in Python? Thank you
char a[]={'0','p','a','s','s','w','o','r','d','1'};
for(int i=1;i<=3;i++) {
try {
WebElement element = driver.findElement(By.id("pff"+i));
if(element != null) {
String indx=element.getAttribute("num");
int k=Integer.parseInt(indx);
element.sendKeys(""+a[k]);
}
}
catch(Exception e){
}
}
Upvotes: 1
Views: 121
Reputation: 864
Firstly, you should learn python. It is not that difficult if you know Java already. As for the function calls nomenclature in python they are slightly different from here
I hope this works for you, I don't know selenium but this should work
# In python comments are preceded by a hashtag
# In python you don't have to declare the type of a list
# A will be an array of the letters
a = ['0','p','a','s','s','w','o','r','d','1']
# Pay attention to your indentation, you should read up on it
# indentation is very important in python
# loop that goes from 0 to 3 (4 here because it's not inclusive)
for i in range(0, 4):
# try statement
try:
# in python you don't need to declare the type of a variable
webElement = driver.find_element_by_id("pff" + str(i))
if element != None:
# to get the attribute you call this method
indx = element.get_attribute("num")
# this is how you parse in python
k = int(indx)
element.send_keys("" + a[k])
except: #here you have to check for which error
print("An error has occurred")
And more concisely, it would look like this:
a = "0password1"
for i in range(0, 4):
try:
if driver.find_element_by_id("pff" + str(i)) != None:
element.send_keys("" + a[int(element.get_attribute("num"))])
except:
print("An error has occurred")
Upvotes: 1