Home > Mobile >  Unable to Get Selenium Python driver.execute_script to Work
Unable to Get Selenium Python driver.execute_script to Work

Time:06-09

I am currently trying to send information to an input field in Chrome. I am working with variables when using the driver.find_element function.

What I have tried:

    ProjectID = '"'   str('driver.find_element(By.XPATH, "//input[@ID='   "'"   '_obj__TIMESHEETITEMS_'   str(rowCounter)   '_-_obj__PROJECTID'   "']"   '").send_keys('   "'"   str(nonProjects['Projects'][rowCounter-2])   "'"   ')')   '"'

After the variables are applied, it looks like this when applying print(ProjectID):

"driver.find_element(By.XPATH, "//input[@ID='_obj__TIMESHEETITEMS_2_-_obj__PROJECTID']").send_keys('OMSH001')"

I also tried without the quotation marks in the front:

ProjectID = str('driver.find_element(By.XPATH, "//input[@ID='   "'"   '_obj__TIMESHEETITEMS_'   str(rowCounter)   '_-_obj__PROJECTID'   "']"   '").send_keys('   "'"   str(nonProjects['Projects'][rowCounter-2])   "'"   ')')

Which looks like this when applying print(ProjectID):

driver.find_element(By.XPATH, "//input[@ID='_obj__TIMESHEETITEMS_2_-_obj__PROJECTID']").send_keys('OMSH001')

I am calling the variable with:

driver.execute_script(ProjectID)

The error I am getting without the quotation marks is that the driver is not defined. When applying the quotation marks, that error goes away, but then the program does not do anything.

Any help is greatly appreciated, as I have been stuck on this error for days.

CodePudding user response:

When looking at your examples, it seems as if you would try to use the selenium api in execute_script and this is obviously not possible.

ProjectID = '"'   str('driver.find_element(By.XPATH, "//input[@ID='   "'"   '_obj__TIMESHEETITEMS_'   str(rowCounter)   '_-_obj__PROJECTID'   "']"   '").send_keys('   "'"   str(nonProjects['Projects'][rowCounter-2])   "'"   ')')   '"'
driver.execute_script(ProjectID)

The execute_script method executes the given JavaScript code directly in your browser and therefore whatever you want to do must be pure JavaScript.

It seems to me, as if in your example you do not need execute_script in the first place as you only directly call the selenium api.

I was not really able to fully unterstand your code, but would strongly suggest to simplify it it into something like this:

xpath = "//input[@ID='{}{}_-_obj__PROJECTID]".format(_obj__TIMESHEETITEMS_, rowCounter)
element = driver.find_element(By.XPATH, xpath)
element.send_keys(str(nonProjects["Projects"][rowCounter - 2]))
  • Related