Unable to enter value to input box with 'OnKeyPress' attribute - Selenium Python - python

I want my code to enter value in the box below and move to the next page. I'm using selenium in Python to do this.
This is the HTML for the element.
<input name="ctl00$SPWebPartManager1$g_d6877ff2_42a8_4804_8802_6d49230dae8a$ctl00$txtPageNumber" type="text" value="260" maxlength="5"
onchange="return ValidateNumber(this);setTimeout('__doPostBack(\'ctl00$SPWebPartManager1$g_d6877ff2_42a8_4804_8802_6d49230dae8a$ctl00$txtPageNumber\',\'\')', 0)"
onkeypress="if (WebForm_TextBoxKeyHandler(event) == false)
return false;javascript:return isNumber(event);" id="ctl00_SPWebPartManager1_g_d6877ff2_42a8_4804_8802_6d49230dae8a_ctl00_txtPageNumber"
onpaste="return false;" style="width:60px;">
This is my code. How should get this to perform 'onkeypress' function?:
for i in range (2,10307): #looping over the page numbers
wait.until(EC.presence_of_element_located((By.ID, "ctl00_SPWebPartManager1_g_d6877ff2_42a8_4804_8802_6d49230dae8a_ctl00_txtPageNumber"))).send_keys(i)

after waiting for the element, since you need only the function onkeypress, try execute script.
driver.execute_script("if (WebForm_TextBoxKeyHandler(event) == false) return false;javascript:return isNumber(event);")

Related

Selenium Python Checkbox Click

I am trying to access the following HTML checkbox for a button click:
<input type="checkbox" data-ng-value="sf.name" data-ng-model="sf.checked" ng-click="ec.onStateFilterChanged(sf)" title="Select a state" class="ng-untouched ng-valid ng-dirty ng-valid-parse" value="Arizona">
using:
state = driver.find_element_by_xpath("input[#type='checkbox']").click()
but keep getting error:
selenium.common.exceptions.NoSuchElementException: Message:
what might be the element path I am looking for in order to select the checkbox?
Your xpath is most likely incorrect - you need to enter // before the element as this will find all (single slash / will work here too though as you are only trying to find one element and it will find the first match)
Try one of the following:
state = driver.find_element_by_xpath("//input[#type='checkbox']").click()
OR
state = driver.find_element_by_css_selector("input[type='checkbox']").click()

Get a html site "input" element by python selenium

I'm really stuck here.
I use Python + Selenium to automate a website form filling.
So I gave some data into the webpage, then "click" on a button, after that a new value appears in an element and I would like to get that value, but I stuck.
How should I get that value into a variable?
I tried to use find_element_by_xpath what works for "click", works for "send.keys", but to get any value from here, nothing.
Please help me!
Picture enclosed about the webpage inspection.
1
'''python
from selenium import webdriver
browser = webdriver.Chrome('chromedriver.exe')
browser.get('https://...')
browser.find_element_by_xpath('//input[parameter-
name="moduleId"]').send_keys('1234')
'''
So by that point everything is ok. I can fill the "moduleId" element with the 1234 value.
but from here I cannot read it back.
so If I try like this:
'''python
moduleId = browser.find_element_by_xpath('//input[#parameter-name="moduleId"]')
'''
the output is nothing.
Here is the HTML part of the website what is interesting.
html
<input type="text" name="parameterValue" class="form-control"
placeholder="Value" spellcheck="false" autocomplete="off" data-bind="value:
value, valueUpdate: 'keyup', autocomplete: { options: options, filtered:
true }, attr: { 'parameter-name': name, type: inputType }" parameter-name="moduleId">
Use this to get the value of the input element:
input.get_attribute('value')
You could also do this all in one shot, example
browser.find_element_by_xpath('//input[#parameter-name="moduleId"]').get_attribute('value')
Thx4 #scilence
I made this modification:
moduleId = browser.find_element_by_xpath('//input[#parameter-name="moduleId"]')
moduleId_value = moduleId.get_attribute('value')
print("data: ",moduleId_value)
and the output is what I need!

creating for loop using selenium python to click dropdown items

I am trying to create a for loop which:-
1) clicks the dropdown item
2) add a comment
3) submit a comment
This whole loop will happen in the same page itself. The XPath is correct and I can execute these lines individually once but it fails in a loop. What am I doing wrong here?
No particular error message given
add_comments = driver.find_elements_by_class_name('add')
comments = driver.find_elements_by_xpath("//form[#class='addComment expand']//textarea[contains(#placeholder,'Add a comment')]")
submit_comments = driver.find_elements_by_xpath("//button[text()='Comment']")
i = 0
for add_comment in add_comments:
for comment in comments:
for submit_comment in submit_comments:
WebDriverWait(driver, 5)
add_comment.click()
comment.click()
comment.send_keys("Awesome Art")
WebDriverWait(driver, 2)
submit_comment.click()
i += 1
if i > 4:
driver.close()
Link is https://society6.com/society?show=2 but might not work since its within my account. Here is the screenshot
The '+add comment is the part where i want to put comment
Html is here-
<form class="addComment expand" data-id="9647336">
<img src="https://ctl.s6img.com/society6/img/g2taHIrokQ01R_67jS8ulaWI2wk/h_150,w_150/users/avatar/~artwork/s6-original-art-uploads/society6/uploads/u/sul97/avatar_asset/d837ee10016843a3bba9ae3310cc338d" width="25" height="25">
<textarea placeholder="Add a comment..." data-button="9647336"></textarea>
<button id="b9647336">Comment</button>
</form>

selenium in python browser.find_element_by_name('submit').click() not working

I'm trying to scrape a site that needs login information, and after hours of trying to figure out why I keep getting "Login failed", I believe it is simply because the "Log in" or "Submit" button is not actually getting clicked. I realized this by saving a screenshot of the browser right when it "fails". My username and password are filled into the fields.
I've tried things like wait, elementScrollBehavior, nothing seems to work. I'd really appreciate some help with this! Code below.
def load(self):
global browser
DesiredCapabilities.PHANTOMJS["elementScrollBehavior"] = 1
#browser field
browser = webdriver.PhantomJS()
wait = WebDriverWait(browser, 10)
#browser = webdriver.Firefox()
#browser = webdriver.Chrome()
loginId = self.id
password = self.pw
browser.get('https://link.example.com')
browser.find_element_by_id('cf-login').send_keys(loginId)
browser.find_element_by_id('password').send_keys(password)
browser.find_element_by_name('submit').click()
#wait.until(EC.presence_of_element_located((By.ID, "crefli_HC_SSS_STUDENT_CENTER")))
try:
if browser.find_element_by_id('crefli_HC_SSS_STUDENT_CENTER'):
#return login status
return True
else:
return False
except:
print('element not found on page')
print(browser.current_url)
#browser.save_screenshot('~/Desktop/screen2.png')
HTML of form:
<form name="loginform" action="/oam/server/auth_cred_submit" method="post">
<div class="nonfloat-box">
Username:
<input type="text" id="cf-login" name="username" class="username inputbox" autocomplete="OFF">
</div>
<div class="float-box">
Password:
<input id="password" name="password" type="password" class="password inputbox" autocomplete="OFF">
</div>
<input type="image" src="https://www.cuny.edu/site/citizencuny/cunyfirst-login/loginbutton.jpg" onclick="javascript: return signon_validate()" alt="Submit" name="submit">
</form>
I believe I need to SOMEHOW get that bit of javascript to run. But HOW?
UPDATE: Selenium has a submit() method that automatically submits the <form> in HTML. Even using this, it does not work. As you can see in the HTML, it IS a form. At this point I do not know what else to try.
Please try this, hope it helps
from selenium.webdriver.common.keys import Keys
driver.find_element_by_name('submit').send_keys(Keys.RETURN)
(or)
driver.find_element_by_name('submit').send_keys(Keys.ENTER)
I have a feeling 'submit' is not being found by find_element_by_name. Try find_element_by_xpath(//*[#name='submit'])
HTML is needed to make a more accurate determination, but I usually use enter key to submit forms, sometimes javascript messes up the ability to submits by click and a simple enter usually does the trick
from selenium.webdriver.common.keys import Keys
def load(self):
(...)
browser.find_element_by_id('password').send_keys(password)
browser.find_element_by_id('password').send_keys(Keys.ENTER)
(...)
Otherwise, make sure you mean find_element_by_name and not find_element_by_tag_name.
Use xpath, Please try this
//input[#name='submit']
or
//input[contains(#name,'submit')AND contains(#alt,'Submit')]
You can use submit() to submit the form. It needs to be sent to the <form> tag
browser.find_element_by_id('cf-login').send_keys(loginId)
browser.find_element_by_id('password').send_keys(password)
browser.find_element_by_name('loginform').submit()
If this doesn't work you can use JavaScript click as a work around
submit = browser.find_element_by_name('submit')
browser.execute_script("arguments[0].click();", submit)
You can also try sending Enter
from selenium.webdriver.common.keys import Keys
browser.find_element_by_id('cf-login').send_keys(loginId)
password_field = browser.find_element_by_id('password')
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
#OR
password_field.send_keys(Keys.ENTER)
When you use selenium do automatic testing or scraping ,I suggest you use the method
webdriver.find_element_by_xpath(xpathString)
because you can check the xpathwebbroser's console
Try this command on console:
$x('xpathString')

Selenium input text that has dropdown & hidden values

I am writing a python script to input text, that then has a dropdown appear to select from a list of items. These items are all hidden values and are not inputted to the webpage until selected by clicking on said item.
Specifically I am attempting to input data on Fitbits website to track food (a thing for work, but it is tedious to input food consumption each day). I would like to automate this :)
My script currently looks like this...
#! python3
# fitbitSubmitFood.py this script submits the food log on fitbit.com
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
# open webpage to log food
browser.get('https://www.fitbit.com/foods/log')
# login to the website
# email username input
emailSelect = browser.find_element_by_xpath('//*[#id="loginForm"]/fieldset/dl/dd[1]/input')
emailSelect.send_keys('EMAIL')
# email password input
inputPassword = browser.find_element_by_xpath('//*[#id="loginForm"]/fieldset/dl/dd[2]/input')
inputPassword.send_keys('PASSWORD')
# click log in
clickLogin = browser.find_element_by_xpath('//*[#id="loginForm"]/div[1]/button')
clickLogin.click() # clicky click!
# input What did you eat?
foodSelect = browser.find_element_by_xpath('//*[#id="foodselectinput"]')
foodSelect.send_keys('Pizza, Bread') # select by visible text
# input How Much?
howMuch = browser.find_element_by_xpath('//*[#id="quantityselectinput"]')
howMuch.send_keys('3')
# click Log Food
logfood = browser.find_element_by_xpath('//*[#id="foodAutoCompButton"]')
# logfood.click() # clicky click!
# Close web browser
The current script above throws the following error.
selenium.common.exceptions.InvalidElementStateException: Message: invalid element state
So I have also tried suggestions from this stackoverflow question.
Entering a value into a type="hidden" field using Selenium + Python
WebDriverWait(foodSelect, 10).until(EC.visibility_of_element_located((By.XPATH,'//*[#id="foodId"]'))) # wait for hidden text to populate
This threw the following error...
selenium.common.exceptions.TimeoutException: Message:
Here is a snippet from the website
input type="text" name="foodselectinput" id="foodselectinput" class="text columnFull yui-ac-input" maxlength="80" tabindex="1" autocomplete="off"
I can see the following on the website for the hidden value. This value is not passed to the webpage until after the food is selected from the drop down menu.
input name="foodId" id="foodId" type="hidden" value="13272"
Note: I have already tried using the click method for the Pizza, Bread
clickFood = browser.find_element_by_xpath('//*[#id="foodselectcontainer"]/div/div[2]/ul/li[1]/div/div[1]')
clickFood.click() # click it!
This did not work.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="foodselectcontainer"]/div/div[2]/ul/li[1]/div/div[1]"}
The script cannot continue until the food item is selected on the webpage. Hence, the question.
How would one pass the hidden value or select from a dropdown?
From your snippet
input type="text" name="foodselectinput" id="foodselectinput" class="text columnFull yui-ac-input" maxlength="80" tabindex="1" autocomplete="off"
yui-ac-input refers AutoComplete from YUI 2 Library (That's what I thought)
As the site mentioned by you asked credentials. I created a sample code for YUI Example
Sorry I dont know python.Below is a Java code. The syntax looks more or less same. So get the idea from below code and implement it
public void start() {
driver.get("http://yui.github.io/yui2/docs/yui_2.9.0_full/examples/autocomplete/ac_basic_array.html");
yuiAutoSuggestSelect("Cali");
}
public void yuiAutoSuggestSelect(String value) {
WebElement inputElement = driver.findElement(By.className("yui-ac-input"));
inputElement.sendKeys(value);
By autoSuggSel = By.xpath("//div[#class='yui-ac-container']//div[#class='yui-ac-bd']//li");
WebElement autoSuggestEl = driver.findElement(autoSuggSel);
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(autoSuggestEl)).click();
}

Categories