Home > OS >  Selenium Python : Excuting javascript code, but it deosnt take effect
Selenium Python : Excuting javascript code, but it deosnt take effect

Time:04-21

I am trying to change the text of a div. I tried to change it by (send_keys) function, but it didn't work. So I tried to change it with java script, like so :

element = self.chrome.find_element_by_xpath('//div[@]')
self.chrome.execute_script("arguments[0].textContent = 'hello world'", element)

Note: I am trying to change the text of the div because this div is the container of an email message

It worked but then When I click on the button "send", it send an empty email. Is there a way that I Confirm The text I changed ? or something in javascript that do that kind of stuff ?

CodePudding user response:

In all likelihood, you are successfully editing the text of the div, but your change is not being picked up by the JS event listener which sets the email body string when you click send.

When filling out forms, send keys is the correct approach, which leads me to believe you are not selecting the proper element to type into. You would expect to see an input field (<input type="text" ...>) or maybe a textarea (<textarea ...>) as the element which has focus when the user types.

The first thing to do is to click on the input field you desire to type into, then right-click on it and inspect element, which should lead you to the innermost element you type into. It's probably not a div (although it may be contained in one).

In the bizarre scenario they do have you type into a div, you appear to have done the right thing. Although typically the quotations are done differently, and its possible due to the subtleties between the textContent and innerText attributes that you might want to try:

element = self.chrome.find_element_by_xpath("//div[@class='ace_line']")
self.chrome.execute_script("arguments[0].innerText = 'hello world'", element)

In this unlikely scenario you'd probably want to click on the div to give it focus and/or type by sending keys so that your typing is picked up the JS keypress listener the site would need to have configured.

Bottom line: You should first use the chrome/firefox inspector and document.getElementBy... in the console to figure out what is actually going on in the webpage. There should be some input element (var input = document.getElementBy...;) you can select in the console whose value property (input.value) will change as you type. Find/muck with this element programatically in the console, confirming that it sends the email with the desired body, then you can code it up in python.

  • Related