Rewrite click() method in Selenium 2 (python) - python

I'm using Seleniun 2 webdriver (python) to run auto tests on IE browser.
One of major bugs in IE webdriver is that click() method does not work in 100% of cases. It happens sometimes when IE browser cannot set/looses focus on element. So, there's a workaround i googled to solve the problem- first the parent element must be clicked/selected. After that click() on the current element always works.
I would like to add my own method, named for ex. ieclick() that would do something like:
element = driver.find_element_by_id('id')
parentElement = element.find_element_by_xpath('..')
parentElement.click()
element.click()
Instead of writing all this code i would like to make:
driver.find_element_by_id('id').ieclick()
But i don't know how to implement this. I'm lost in Selenium modules code. I know that selenium class has click() method but i can't understand how can i rewrite it/add my own and make it useble for all this find_element_by_id, find_element_by_xpath etc.
Can someone help me to understand this implementation or maybe paste a link to some sort of explanation/example/lesson ?

The only reason that an element would not receive a click is because :
The element is disabled.
The element is invisible (therefore, cannot interact with it)
The element is not listening for any clicks (not binded)
My guess is that your "inconsistency issue" is coming form the third reason.
Consider the following:
<a href="dosomething">
<span id="spanclick">Click me</span>
</a>
Doing driver.find_element_by_id("spanclick").click() would not work, because it's the <a> element that is receiving the click, not the <span>.
It's your responsibility as the test writer to determine which element is receiving the click. My suggestion would be use debugging anytime you are in doubt. I've actually had a scenario where an <li> was receiving the actions of the mouse, not the <a>. By using Watch Expressions you are able to find what element is receiving the actions.

Seems i was exaggerating the difficulty.
selenium\webdriver\remote\webelement.py
Added code right after native click() method:
def ieclick(self):
"""2013-12-27. Surely clicks the element in IE."""
parent = self.find_element(by=By.XPATH, value='..')
parent._execute(Command.CLICK_ELEMENT)
try:
self._execute(Command.CLICK_ELEMENT)
except:
pass

Related

Selenium: Can't find element by class name in any way

I have this problem where I can't access a button trough it's class name in any way I could think of.
This is the HTML:
<button class="expand-button">
<faceplate-number pretty="" number="18591"><!---->18.591</faceplate-number> weitere Kommentare anzeigen
</button>
I tried to access it using:
driver.find_element(By.CLASS_NAME, "expand-button")
But the error tells me that there was no such element.
I also tried X-Path and Css-Selector which both didn't appear to work.
I would be glad for any help!
Kind Regards and Thanks in advance
Eirik
Possible issue 1
It could be because you check before the element is created in the DOM.
One way to solve this problem is by using the waites option like below
driver.implicitly_wait(10)
driver.get("http://somedomain/url_that_delays_loading")
my_dynamic_element = driver.find_element(By.ID, "myDynamicElement")
You can read more about it here: https://www.selenium.dev/documentation/webdriver/waits/#implicit-wait
Another way is by using the Fluent Wait whhich marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
#Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
#Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
#Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
#Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)
#specify the condition to wait on.
wait.until(ExpectedConditions.element_to_be_selected(your_element_here));
you can also read more about that from the official documentation
https://www.selenium.dev/documentation/webdriver/waits/#fluentwait
Possible issue 2
it is also possible that the element might be partially or completely blocked by an element overlaying it. If that is the case, then you will have to dismiss the overlaying element before you will be able to perform any action on your target

Check AngularJS checkbox with Selenium

HTML Source here
It seems trivial, but after hours of attempts I cannot manage to check this checkbox using Selenium. I am able to select the element no problem, and have even been able to 'highlight' (see code snippet below) it by sending Keys.RETURN to the element, but on attempting to click it, nothing happens. Perhaps someone has an idea?
What I have tried already:
Using with WebDriverWait
Using multiple and different combinations of .click()/.send_keys(Keys.RETURN)
Just about every combination of XPATH/css selector/id/name/classname/text that Selenium would accept for the element, and all of its children and most of its parents (including spans/labels, and the text inside the label itself).
Directly clicking the element/label coordinates using actions (nothing happens, even when I can 100% confirm it is clicking the right spot by using context_click()).
Using execute_script to change the "checked" attribute to True (the checkbox appears checked, but it is clear it is only client side as a box that is supposed to render when it is actually clicked doesn't).
Using execute_script to change the class to 'ng-valid ng-not-empty ng-dirty ng-valid-parse ng-touched'
Here is the code that I feel got me the closest (it is 'highlighting' the box as seen here)
browser.find_element(By.ID, "sp_formfield_none_of_the_above").send_keys(Keys.RETURN)
Managed to solve it after another while of testing. Hopefully this helps someone in the future. I had to use JS to execute .click() on the checkbox element. In retrospect, I should have tried this solution sooner. See code snippet:
cb_none = browser.find_element(By.ID, 'sp_formfield_none_of_the_above')
browser.execute_script("arguments[0].click();", cb_none)

Finding XPath without using inspecting element?

I am making an automation for download data from a weather institution.
The issue is that in my effort to make it more independent I am trying to make Selenium to Tab keys to a certain spot, so the Browser focus can "Walk" to the download button. When I call the click() function it doesn't do anything. So I tried to Extract the XPath with the function get_attribute("xpath") but it returns None. How I can extract the XPath?
I am going to paste the issue down here:
Bandera=driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[3]/div/div/div/div[1]/div/div/div[2]/div/table/tbody/tr[1]/td[1]/div/input')
Bandera.click()
Bandera.click()
## So Here i just select and dis-select a checkbox just to be near the Download button.
actions = ActionChains(driver)
actions.send_keys(Keys.TAB * 1 )
actions.perform()
#Here i just tabed to the button
Accion=driver.switch_to.active_element
#Maybe, here is when i lost the focus of the button?
Descarga_Actual=Accion.get_attribute("xpath")
Thank you and sorry to borrow your time.
To make a click on hover I would use the following sequence:
your_dropdown_locator.click()
dropdown_option = driver.find_element_by_xpath("dropdown option locator")
actions = ActionChains(driver)
actions.move_to_element(dropdown_option)
actions.click().perform()
But, this is the approach that is usually used for dropdowns.
You use: driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/div[3]/div/div/div/div[1]/div/div/div[2]/div/table/tbody/tr[1]/td[1]/div/input') This is the main problem of your code.
If you pasted html code of this dropdown (or button you need to click), people would help you to find a better locator. XPath/CSS must be unique. In your case the locator is very bad.
Also, I see no sense making Bandera.click() two times.
In your case, as I understand, you just need to click the button. So the locator is your main problem.
You need to find the correct locator, to wait till the button is clickable and then to click it.
Another problem in what you are trying to do:
get_attribute("xpath") looks like incorrect expectation of how get_attribute function works. Check at least here what this function means Python Selenium: Find object attributes using xpath

Selenium not detecting an element

So I'm coding this bot to join my school classes for me using selenium and I'm facing this issue where it goes to my conferences page and it waits for a join button to appear and press on it. At first, it wouldn't be able to find it so I scratched the idea of time and I made sure that when it opens the page the join button will be there so I did that and even put this line of code just to make sure
join=WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH,"//span[contains(text(),'Join')]")))
yet it still can't find the join button either press it even though it's visible by the eye I will link the page source under in a link if you can just tell me how to find it also I cant use the href method since it isn't stored like that it's just stored like this
https://i.stack.imgur.com/ldxY7.png
so I'm really confused it's almost like this is an invisible element its funny because even when I do get an error I use control F on inspect element to check if I used correct XPATH and I always find it so I don't see why selenium cant please help I think I just missed something I just don't know what.
Page Source
Check the presence of the element by looping and checking the presence_of_element_element_located multiple times with 2/3 seconds delay added between every consecutive check.
An analogy from python selenium-
for i in range(5):
l= driver.find_element_by_css_selector("#js-gdpr")
time.sleep(5)
OR
Iterate over all the elements under the parent div and verify it using unique text/color and access it.
I think you are trying to do Google meet automation. In that website the "join now" button is declared as a dynamic path so, you can use the library pyautogui
impor pyautogui as pg
for i in range(5):
pg.press('tab')
time.sleep(2)
pg.press('enter')
This code will help you to find the join now button and to click it.

With selenium on python don't know how to shut down a banner which is preventing selenium from accessing the page content

I'm trying to open a site with Selenium (with Python) using Chrome browser, but when I do, a full screen promo banner immediately pops-up and I can't access the site content unless I close it.
On the top right there is an "x" as if it was a quit button, but actually it's an element ::before
and from its description it seems to me that it doesn't contain any button element.
If I operate manually, both clicking on the x and on the upper part of the page outside the banner, the latter closes, but I really don't understand how to access it with selenium.
The webpage I'm trying to open is https://sports.bwin.it/it/sports
Needless to say I'm quite inexperienced, so I hope this question won't sound too basic, but I wasn't able to find a solutione in the selenium docs or on the web; if someone could give me any hint I would appreciate it.
This is a screenshot from the page I'm talking about
This is part of the html code from the web page; the element I am talking about is the one pointed by the arrow;
Based on your screen shot the xpath you want to use would be something like this:
//*[#data-id='dj_sports_c_ovl_br']//span
full code would be something like this:
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//*[#data-id='dj_sports_c_ovl_br']//span"))
)
element.click();

Categories