Selenium webdriver - Python won't click a button on a website - python-2.7

This is my first question on Stack Overflow. I am not much of a programmer, I just learnt about Selenium and went as far as I could but there is this mistake I can't fix alone so I am asking for help. I am using Python 2.7 in PyCharm.
As of now, I have been using anything.send_keys(Keys.ENTER) to click some buttons in my code as the .click() function always returned me a ElementNotInteractableException error in Chrome for this website. The goal here is simply to clear a text area, insert the list of genes down there and click on this "submit" button. This is supposed to show me an updated table that I want to download.
For this one troublesome button though, nothing works. The thing is, it doesn't even return an error, the code keeps going on as if it indeed had clicked, and it eventually downloads the non-updated table. I tried switching to Firefox, where neither .click() nor .send_keys(Keys.ENTER) worked (I never get an error as well, it just downloads the wrong table). Clicking myself does work and produces the updated table.
Based on other questions I saw here, I tried using ActionChains or scroll_into_view but still, nothing happens. Here is the code :
baseline_url = "http://mtsspdb.noble.org/atlas-internal/3880/transcript/profile/5?charttype=barchart&sessionid=1553076490500118&feature_accs=%20Medtr1g079760.1"
driver = webdriver.Chrome("C:\Webdrivers\chromedriver.exe")
driver.set_page_load_timeout(30)
driver.get(baseline_url)
driver.maximize_window()
peptides_list = """Medtr4g068220.1
Medtr1g107390.1
Medtr1g018740.1
Medtr5g016470.1
Medtr4g095002.1
Medtr5g004930.1
MT4Noble_020581.1
Medtr1g107395.1
Medtr1g107400.1
Medtr1g107405.1
Medtr1g107410.1
Medtr4g095010.1
MT4Noble_057127.1
"""
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//*[#id='feature_accs']")))
text_area = driver.find_element_by_xpath("//*[#id='feature_accs']")
text_area.clear()
text_area.send_keys(peptides_list)
time.sleep(1)
troublesome = driver.find_element_by_xpath("//*[#id='form1']/div[8]/div/input")
print troublesome
#scroll_into_view = troublesome.location_once_scrolled_into_view
ActionChains(driver).move_to_element(troublesome).send_keys(Keys.ENTER)
time.sleep(3)
print "Sucess for x"
The html location of this button is
<input class="btn btn-primary" type="submit" name="submit" value="Submit">
Do you have any idea on how to click it, and most of all on why it doesn't work ?
Many thanks
PS: As I said previously, it is my first question. Please tell me if I need to update/change something.

This will definitely work, as I just tried it given your information
driver.execute_script("$('#form1').find('.btn-primary').click()")
Now, there must be something strange about it finding the element, as Selenium would error if it could not click. So the element we are clicking with the code must not have the events we expect it to have. I am investigating more and will update this with specifics.
Edit:
Interesting. The submit button does not seem to have normal event listeners.
getEventListeners($(".btn-primary")[0]);
$._data($(".btn-primary")[0], "events");
Both of these return nothing. This would seem to be the cause of the Selenium issue. It isn't triggering the actual submission with its click. Selenium does not use Javascript, and also does not use a real user32.dll (Windows ex) click, so it does not always behave identically to a real click or a javascript click.

Welcome to SO. Here is the option to click on the button.
Option 1: click using javascript
driver.exeucte_script("arguments[0].click();",troublesome)
Option 2: Scrolling to element
troublesome.location_once_scrolled_into_view
troublesome.click()

This works well for me:
for i in range(1, 10):
try:
driver.find_element_by_xpath(
f'/html/body/div[{i}]/div/div[2]/span[1]/span/span/input').click()
except:
pass

Related

How to show textInput and keyboard programmatically

I'm in charge to a build a react-native chatbot app, that must help users to signup during the discussion.
The chat must start with a greeting message and few quick-replies, in which we find a "Sign me up" option. When the user presses that option, the bot asks hem to write an email address in order to start the process.
I've made a little project based on the example available on react-native-gifted-chat repository.
Please use this link to get to my code: https://github.com/firas1220/react-native-chatbot
I'd appreciate if someone gives some hand or maybe we can add improvements and transform the repo into something original 😉.
This question might help some people facing similar situations.
As an attachment, a demo in GIF image.
Just add an InputText (https://reactnative.dev/docs/textinput) and then to ref.current.focus()
Something like this:
const inputRef = useRef();
const onAction = () => {
inputRef.current.focus();
}
<InputText ref={inputRef} value=... />

How To set aria-pressed="true" in Selenium?

HTML:-
<ion-segment-button class="segment-button" role="button" tappable value="sign_in" aria-pressed="false">
Selenium Code:-
WebDriver driver = new ChromeDriver();
driver.get("URL");
WebElement Login =driver.findElement(ByClassName.className("segment-button"));
Login.submit();
How To set aria-pressed="true" in Selenium??
There is no direct way to set the attribute of a element in selenium. But we can use the javascript Executor to set attribute of a element as given below.
WebDriver driver = new ChromeDriver();
driver.get("URL");
WebElement Login =driver.findElement(ByClassName.className("segment-button"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].setAttribute('aria-pressed',true);",Login);
The short answer is don't. Don't do this unless you really know what you are doing and understand the site. Forcing values on elements using JS shortcuts all the events that the site has to handle this user flow and you could put the page in a bad state. No user is going to run JS on the page to put it in the desired state... your script shouldn't either.
The right way to do this is to figure out how this gets set from a user's perspective. What buttons do I have to push, etc. to get the desired setting? Once you figure that out, write the Selenium code to push those buttons, etc. and you will have the desired result.

Pywinauto 0.6.0 access browser URL in edit control for Firefox

I am currently trying to access URL of the active window for Firebox browser using Pywinauto 0.6.0, as part of a python app that can track website usage. I am a newbie python programmer, so if I have made some obvious mistakes then this is why.
I have read all the material I can find on Google and the Pywinauto docs, but there are no clear indications of how to do this, atleast not without using "Typekeys" after connecting to a window.
In fact, I have been able to access to the URL the "hack" way by connecting to the browser window with pywinauto, then using "TypeKeys()" to grab the URL and copy it to clipboard. But this approach will not work for me, as it interrupts the user and my app must run in the background whilst the user is accessing their system as usual. Using the typekeys method introduces some odd mouse and window behaviour when changing or refreshing windows and then trying to grab the URL - so the approach has proven unworkable for me.
Currently the code I have is as follows (I have used the window text title='' of a specific window I am using for testing, in practice it is whichever the active tab on the browser is):
from pywinauto import *
app = application.Application()
app.connect(title=u'Facebook - Log In or Sign Up - Mozilla Firefox', found_index=0)
window = app.top_window_()
window.PrintControlIdentifiers()
titlebar = window.child_window(title=u'Facebook - Log In or Sign Up - Mozilla Firefox')
toolbar = titlebar.child_window(title=u'Navigation Toolbar')
combobox = toolbar.child_window(title=u'Search or enter address')
edit = combobox.child_window(title=u'Search or enter address')
I use PrintControlIdentifiers() in order to see which elements I can interact with, but this returns only
MozillaWindowClass - 'Facebook - Log In or Sign Up - Mozilla Firefox' (L-32000, T-32000, R-31840, B-31944)
[u'Facebook - Log In or Sign Up - Mozilla Firefox', u'MozillaWindowClass', u'Facebook - Log In or Sign Up - Mozilla FirefoxMozillaWindowClass']
I can access the Firefox Window fine with the current active tab, but next when trying to access the ChildWindow and subsequent ChildWindow there is no error, until I try and do something with the childwindow e.g., Click() function on what I think in the URL bar UI element. However, I am not sure even if the code is even accessing the child window element correctly in the first place. Or if this the right way to try and filter through the child elements to get to the URL edit control element.
As can be seen in the below image of the tree view of the UI elements (using UISPY.exe), the following tree to access the firefox browser edit control element that contains the URL is:
Tree view of Firefox UI elements via UISPY
"window" -> "title bar" -> "tool bar" "Navigation Toolbar" -> "combo box" -> "Search or enter address" -> "edit" "Search or enter address
where the "edit" control contains the attribute Value, Value:"url", which I need to extract to a variable.
Any help with this would greatly appreciated.
This is probably too late to post but incase any future developers has similiar question. Here is working solution.
Just pass backend='uia' as argument like application.Application(backend='uia'). Now, accessing and performing actions on child_window is possible.
Here is complete code snippet for any url.
url='https://google.com'
app = application.Application(backend='uia').connect(title_re=".*Mozilla Firefox")
main_firefox_winspec = app.window(title_re=".*Mozilla Firefox")
address_bar = main_firefox_winspec.child_window(title_re=".*or enter address", control_type="Edit")
address_bar.set_edit_text(url)
time.sleep(3)
main_firefox_winspec.child_window(title="Go to the address in the Location Bar").wrapper_object().click_input()

Is there a way to select pictures in a pop-up using Python Selenium?

I am able to do all the basic web actions using Selenium, but I would like to do the following:
Click on a "select image" button, then there comes a pop-up, then I would like to enter some text in #1 and #2, and click #3.
Edition: What I have tried is on kijiji site, after clicking the select image button, I select two images (see picture), then I backward locate these image holder and find the Xpath, then I added the following codes (below), but it doesn't seem to do anything, it gave me some stacktrace message and no error.
imageLoc = "C:\AbsolutePath\IMG_20150620_184908_Edited_sm.jpg"
imageHolderXpath = '(//div[#class="image"])[1]'
imageHolderElement = WebDriverWait(driver, 5).until(lambda driver: driver.find_element_by_xpath(imageHolderXpath))
imageHolderElement.send_keys(imageLoc)
Output:
Message:
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///c:/users/kubik/appdata/local/temp/tmp_sthxl/extensions/fxdriver#googlecode.com/components/driver-component.js:10659)
at FirefoxDriver.prototype.findElement (file:///c:/users/kubik/appdata/local/temp/tmp_sthxl/extensions/fxdriver#googlecode.com/components/driver-component.js:10668)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/kubik/appdata/local/temp/tmp_sthxl/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///c:/users/kubik/appdata/local/temp/tmp_sthxl/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///c:/users/kubik/appdata/local/temp/tmp_sthxl/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
[Finished in 30.3s]
It is not possible via selenium, the Upload File dialog is out of selenium's reach.
By all means, you should avoid this popup being opened in the first place. A common solution to this problem is to find the corresponding file input element and send the absolute path to a file to be uploaded. Sample:
element = driver.find_element_by_css_selector("input[type=file]")
element.send_keys("/absolute/path/to/a/file")
Also see related topics:
How to upload file ( picture ) with selenium, python
selenium webdriver upload file
Well, there are certainly other options, like using AutoIt or Sikuli, but they would really be either unreliable, or complex, slow, platform or browser dependent (or all of it).
Here is a sample working code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.kijiji.ca/p-post-ad.html?categoryId=36")
driver.find_element_by_link_text("British Columbia").click()
driver.find_element_by_link_text("Cariboo Area").click()
driver.find_element_by_link_text("100 Mile House").click()
driver.find_element_by_id("LocUpdate").click()
driver.find_element_by_css_selector("#ImageUpload [type=file]").send_keys("/Users/user/Downloads/test.jpg")
Which produces:

Accessing Firefox tab element in nsIWebProgressListener::OnStateChange using C++

I am developing extension for Firefox 3.0-3.5 versions using VS2008.
I want to set attribute to a tab once the document load request completes within that tab window.
So in OnStateChange method, I am checking for document load.
I have used STATE_STOP & STATE_IS_DOCUMENT for it.
I want to determine which tab window has been associated with particular document request.
I have valid DOM Document pointer got from nsIWebProgress *aWebProgress which is 1st input
parameter of OnStateChange.
if ((aStateFlags & STATE_STOP) && (aStateFlags & STATE_IS_DOCUMENT))
{
nsCOMPtr<nsIDOMWindow> domwin;
nsCOMPtr<nsIDOMDocument> domDoc;
aWebProgress->GetDOMWindow(getter_AddRefs(domwin));
domwin->GetDocument(getter_AddRefs(domDoc));
}
I have tried to get nsIDOMDocumentXBL pointer by QIing nsIDOMDocument pointer(domDoc in my example) but it fails with Error code 0x80004002 (2147500034) i.e.NS_ERROR_NO_INTERFACE.
How do I get the tab element corresponding to document load request.
Could any one please help me?
Thanks in Advance,
Vaibhav D. Gade.
IF I understood the question correctly and you want a for a content window, you probably need https://developer.mozilla.org/en/Working_with_windows_in_chrome_code#Accessing_the_elements_of_the_top-level_document_from_a_child_window to get the chrome window, then run the implementation of gBrowser.getBrowserForDocument in the chrome window.
You'd save yourself a lot of time if you stopped writing C++ and switched to JS for such things.