Python with Selenium - selecting a button or text action - python

I am, poorly, trying to 1. Click a button or 2. Check for text and then execute an action. I think I am just not coding this correctly.
eg
if driver.find_element_by_class_name('classOne').click()
elif:
"No Item" in driver.find_element_by_class_name('classTwo').driver.get(self_base_url)
This seems pretty simplistic, and I'm sure I've done something horribly wrong. This 'should' work, but isn't?

If the driver can't find an element, it will raise NoSuchElementException.
In your case, you can do:
x = driver.find_elements_by_class_name('classOne')
if len(x) > 0:
# click the first one found
x[0].click()
else:
print('No item x was found.')
Notice that I changed it to find_elements_by_class_name from find_element_by_class_name. This finds all elements if there are any and returns a list.

Related

How to make an IF statement and choose between 2 options Selenium python

Im trying to automate Login for a website. Sometimes when i enter the serialnumber of the product and it have been used before it will tell me this serialnumber has been used before, press continue to proceed, this will refer to another button/field/xpath.
This is my problem. When this occurs i want it to press continue. If the serialnumber HAVENT been used before it will click another button/field/xpath. So the program wont crash.
To summarize it, i want python/selenium to choose one of them if one of them is present.
How can i controll this? im new to this and trying to learn.
You can use driver.find_elements method. In case of match, the element exists, it will return a non-empty list of found elements that is interpreted by Python as a Boolean True, otherwise it will return an empty list => Boolean False.
So your code can look like the following:
first_el = driver.find_elements(By.CSS_SELECTOR, 'first_element_selector')
second_el = driver.find_elements(By.CSS_SELECTOR, 'second_element_selector')
if first_el:
first_el[0].click() #or whatever
elif second_el:
second_el[0].click()
else:
print("None of elements found)

Clicking a button with a conditional Selenium

I'm a beginner, learning selenium packpage using python language.
How could I click on the button with the text: "Co-assinar" only when there is the text: 'Segue a certidão..."
I'll put an image below the part of the code I'm talking about.
https://i.stack.imgur.com/8jV64.png
Your best bet is to "collect" the two elements you'd like as variables and then use an if statement to check and see if the elements text is equal to "Segue a..." and in that case click.
Something like this:
#Get the button you want to click
button_to_click = driver.find_element(By.CLASS_NAME, 'menor link_amissao_assinar...')
#Get the element that holds the text you're checking
text_you_want = driver.find_element(By.CLASS_NAME, 'texto_original').children[2].text
#If element text equals 'Segue a...' click
if text_you_want == 'Segue a...':
button_to_click.click()
try:
driver.find_element(By.XPATH,"//p[contains(text(),'Segue a certidão')]")
driver.find_element(By.XPATH,"//a[./i[text()=' Co assinar ']]").click()
except:
pass
You can check for the second element and then click the first element if it's there. Handling any exceptions you may want to in case.

How to select value of drop down list with selenium in python

I have just started my first project with python and already spend hours searching for a solution, but couldn't find anything.
I would like to fill out a website, by selecting values from drop-down list. My problem is that the values of these lists are not hard coded like in the solutions I found in this forum.
I have inspected the website and made three screenshots (before clicking, when clicking and after selecting an item)
before clicking
by cklicking
after selecting
I was able to open the drop-down-list and read all values of the list, but not able to select one of them
css = 'body > main > section > section > div.ut-navigation-container-view--content > div > div.ut-pinned-list-container.ut-content-container > div > div.ut-pinned-list > div.ut-item-search-view > div:nth-child(2)'
iElement = browser.find_element_by_css_selector(css)
SpanVariableValue = iElement.text
#prints selected value or default
print (SpanVariableValue )
iElement.click()
SpanVariableValue = iElement.text
#prints all elemets of drop-down
print (SpanVariableValue)
#drop-down doesn't work after the following code
browser.execute_script("arguments[0].innerText = 'SILVER'", iElement)
Can anybody help me with my problem?
Cheers,
Andi
Edit: Sorry, I made a mistake when adding the screenshots in the original post
Not sure if you already attempted this when looking through the Selenium documentation, you could give the following a try:
Selenium.click()
An example command would look something like this:
element = driver.find_element :xpath, '//input[#name="q"]'
element.click()
You can just set the element xpath to be the elements of the drop down, then Selenium would be able to click the options you want.

for loop selenium python runs the last loop

My for loop goes to the latest part, and because the webpage needs the upper for loops to open so that the other for loops can operate, it doesn't work.
for x in browser.find_elements_by_class_name('node'):
x.click()
for y in browser.find_elements_by_class_name('dTreeNode'):
y.click()
if len(browser.find_elements_by_class_name('node')) > 0:
browser.find_element_by_class_name('node').click()
browser.find_element_by_xpath('/html/body/center[2]/form/table[1]/tbody/tr/td[3]/table/tbody/tr[5]/td[1]/a[1]/img').click()
browser.find_element_by_xpath('/html/body/center[2]/form/table[2]/tbody/tr/td[4]/input').click()
browser.find_element_by_xpath('/html/body/center/form/table[2]/tbody/tr/td[5]/a').click()
browser.execute_script("window.history.go(-1)")
This is the image:
In essence when the page goes back, it can't locate the last loop class and shows up an error because the element can only be found once I click on the previous element. But how do I do that inside the for loop?
Image of the HTML Text:
It seems that either the for y in browser.find_elements_by_class_name('dTreeNode'): returns an empty element or click is performed on a wrong element i.e. element is not programmed to receive the click.
Either case -
First thing - Please check if your first loop executing the code or not.
for y in browser.find_elements_by_class_name('dTreeNode'):
y.click()
print('Clicked the element') #just for debugging
Then see if the element is returned or not.
Secondly - I see you are using absolute xPath. Can you convert it to relative xPath. Refer to XPath Tutorials
If you need help on xPath, update your question and HTML snippet of the expanded tree.

How to use Selenium function back() and I loss my variable in Python?

I'm new to Python.
I met a BIG problem in Python!!
I visit a website and put about 200 options from a dropdownlist in a array.
I want to click every options in the array and click javascript button to submit.
Take something I want from that page and back to previous page click another option.
Do those actions about 200 times in a for loop.
Here is the code:
for option in arrName:
if count > 0:
option.click()
string = u'Something'
link2 = browser.find_element_by_link_text(string.encode('utf8'))
link2.click()
//"do something I want"
browser.back()
count = count +1
In this code, I don't want to use first option.
PROBLEM comes,after the program click the second option, click the link2, and browser.back(), it answer me:
` StaleElementReferenceException: Message: stale element reference: element
is not attached to the page document
that means the options in array disappear?
How should I use the options in the array when the browser.back() in for loop?
Thanks
Yes, this is happening because of DOM refresh. You cannot simply iterate over an array and click back and forth. Best option is to find the element in runtime and then click. Avoid option.click() instead, find the next element with find_element. If you are not sure how to accomplish that then please provide the html

Categories