can't enter text into element in selenium python - python

why i'm getting "InvalidArgumentException" when trying to enter text into angular input element.
NOTE: i'm getting xpath from csv file
class TimeSheet:
def __init__(self):
c_options = Options()
self.__driver = webdriver.Chrome(options=c_options)
self.__action = None
def enter_text_into_element(self):
text = self.__action['enter_text']
element = self.__driver.find_element_by_xpath(self.__action['xpath'])
element.clear()
print('text cleared')
element.send_keys(text)
def click_function(self):
click_status = False
element_clicked = self.__driver.find_element_by_xpath(self.__action['xpath'])
try:
element_clicked.click()
click_status = True
except Exception as ex:
print(ex)
return click_status
ts = TimeSheet()
for index, task in enumerate(tasks):
ts.set_action(task)
print(ts.get_step(), end=": ")
print(ts.get_action())
if ts.get_action() == 'click':
ts.click_function()
elif ts.get_action() == 'text':
ts.enter_text_into_element()
#Error Traceback
Traceback (most recent call last): File
"C:\PycharmProjects\testSelenium\timesheet_automation.py", line 116,
in
ts.enter_text_into_element() File "C:\PycharmProjects\testSelenium\timesheet_automation.py", line 82, in
enter_text_into_element
element = self.__driver.find_element_by_xpath(self.__action['xpath']) File
"C:\PycharmProjects\testSelenium\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath) File "C:\PycharmProjects\testSelenium\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 976, in find_element
return self.execute(Command.FIND_ELEMENT, { File "C:\PycharmProjects\testSelenium\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 321, in execute
self.error_handler.check_response(response) File "C:\PycharmProjects\testSelenium\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
line 242, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid
argument: missing command parameters

Related

Why a JSON error in python selenium request?

I don't understand the following error I have using python selenium. Can you explain please this error?
def getdriver(url):
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.minimize_window()
driver.get(url)
return(driver)
driver = getdriver("https://address.com")
driver.switch_to.frame('idIframeEngagement')
equipes = driver.find_elements(By.CLASS_NAME, 'menu')
for elt in equipes:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable(((By.PARTIAL_LINK_TEXT, elt.text.encode('utf-8'))))).click()
I connect to a webpage. I get all the links I need and the I want to visit all of them using a loop but I get all this error:
Traceback (most recent call last):
File "C:\code\python\Avenir\resu\main.py", line 77, in <module>
getinfoFFBB()
File "C:\code\python\Avenir\resu\main.py", line 57, in getinfoFFBB
WebDriverWait(driver, 20).until(EC.element_to_be_clickable(((By.PARTIAL_LINK_TEXT, elt)))).click()
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\support\wait.py", line 81, in until
value = method(self._driver)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 312, in _predicate
target = driver.find_element(*target) # grab element at locator
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 855, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 426, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 342, in execute
data = utils.dump_json(params)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\site-packages\selenium\webdriver\remote\utils.py", line 23, in dump_json
return json.dumps(json_struct)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\elman\AppData\Local\Programs\Python\Python310-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

python selenium Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'

So I'm getting the error below using python selenium. I want to build a browsergame bot and I'm currently stuck here. Tried to do it mostly with the oop technique, but this didn't really work out for me since I had the bug only since I used the classes ;)
Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
My code:
class Buildables():
def __repr__(self):
return self.sparte, self.toolTip
def __init__(self, ref, sparte, *args, **kwargs):
self.toolTip = lambda: wait.until(
EC.presence_of_element_located((By.XPATH, ('//*[#ref=\'' +
str(ref) + '\']'))))
self.LVL = lambda: int(
wait.until(EC.presence_of_element_located((By.XPATH, ('//*
[#ref=\'' + str(ref) + '\']/span/span')))).text)
self.ausbauButton = lambda: wait.until(
EC.presence_of_element_located((By.XPATH,
('//*[contains(text(),\' Ausbauen\')]'))))
self.sparte = lambda : driver.find_element_by_xpath('//*
[contains(text(),'+ sparte +')]')
metalMine = Buildables(1,'Versorgung')
a = c.metalMine.sparte()
a.click()
What do I do wrong?
BTW full error:
Traceback (most recent call last):
File "C:/Users/leosc/PycharmProjects/ogameBot/ogame_main.py", line 5, in <module>
cycles.buildMinesCycle()
File "C:\Users\leosc\PycharmProjects\ogameBot\cycles.py", line 132, in buildMinesCycle
a.click()
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\leosc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: javascript error: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
(Session info: chrome=72.0.3626.121)
(Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.17134 x86_64)

Python selenium selenium.common.exceptions.StaleElementReferenceException:

I have this weird error with selenium when I try to find sportsbook odds from oddsportal.com. It looks like selenium object does not work like a normal list and I can not just loop over every url. Test url that should work http://www.oddsportal.com/soccer/england/premier-league/ (Script is not written for home-draw-away odds).
So what am I doing wrong here?
My script:
from selenium import webdriver
from selenium.common.exceptions import NoSuchAttributeException,NoSuchElementException
from selenium.webdriver.common.keys import Keys
class Odds():
def odds(self,driver,url):
kertoimet = ['','']
driver.get(url)
odds = driver.find_elements_by_xpath("""//*[#id="odds-data table"]/div/table/tbody/tr""")
for item in odds:
data = item.text.replace(' ','').split('\n')
if data[0] == 'Pinnacle':
kertoimet = [data[1],data[2]]
return kertoimet
def odds_finder(self,data,driver):
for item in data:
if item.get_attribute('href') != '':
print(Odds().odds(driver,str(item.get_attribute('href'))))
def url_finder2(self,URL):
driver = webdriver.Chrome("/usr/local/bin/chromedriver 2")
driver.get(URL) #http://www.oddsportal.com/soccer/england/premier-league/
data = driver.find_elements_by_xpath("""//*[#id="tournamentTable"]/tbody/tr/td/a""")
Odds().odds_finder(list(data),driver)
Odds().url_finder2(URL)
Error:
Traceback (most recent call last):
File "odds.py", line 79, in <module>
Odds().url_finder2(open('oddsportal_odds.csv'))
File "odds.py", line 61, in url_finder2
Odds().odds_finder(list(data),driver)
File "odds.py", line 49, in odds_finder
if item.get_attribute('href') != '':
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webelement.py", line 141, in
get_attribute
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webelement.py", line 494, in
_execute
return self._parent.execute(command, params)
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/Library/Python/2.7/site-
packages/selenium/webdriver/remote/errorhandler.py", line 192, in
check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message:
stale element reference: element is not attached to the page document
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.29.461585
(0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.3
x86_64)
You just need to call data again because the state gets changed.
Try modifying this 2 function.
def odds_finder(self,driver):
for item in driver.find_elements_by_xpath("//*[#id="tournamentTable"]/tbody/tr/td/a"):
time.sleep(5)
if item.get_attribute('href') != '':
print(Odds().odds(driver, str(item.get_attribute('href'))))
def url_finder2(self, URL):
driver = webdriver.Chrome("/usr/local/bin/chromedriver 2")
driver.get(URL) # http://www.oddsportal.com/soccer/england/premier-league/
Odds().odds_finder(driver)

Selenium 2.53.5 httplib.BadStatusLine: '' Python

Im trying to automate the registration of serial numbers in an online form using Selenium 2.53.5 in Python 2.7. The script has been working for 2+ months, but yesterday I started receiving an error right when I go to run it: httplib.BadStatusLine: ''. Is there any known fix for this? I've read that leading/trailing new line characters can mess up the retrieving of the url but I can't seem to identify the issue.
Code:
import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class SerialSet:
def __init__(self, fileName, driverPath, user, password):
self.fn = fileName
self.failedSerials = []
self.driver = webdriver.Chrome(driverPath)
self.aloSuccess = False
self.user = user
self.password = password
def parseSerialFile(self):
with open(self.fn, 'r') as f:
self.serials = [line.strip() for line in f]
def setCountrySN(self, serial, driver):
driver.find_element_by_xpath("//select/option[#value='USA']").click()
driver.find_element_by_id("serialno").send_keys(serial)
driver.find_element_by_xpath("//input[#value='Continue'][#type='button']").click()
def submitState(self, driver):
driver.find_element_by_xpath("//select/option[#value='CT']").click()
driver.find_element_by_id("Continue1").click()
def login(self, driver):
driver.find_element_by_xpath("//*[#id='accountname']").send_keys(self.user)
driver.find_element_by_xpath("//*[#id='accountpassword']").send_keys(self.password)
driver.find_element_by_xpath("//*[#id='signInHyperLink']").click()
def initiateSN(self, serial, driver):
# select country and enter serialno
driver.get("http://supportform.apple.com/201110/")
self.setCountrySN(serial, driver)
# enter login
time.sleep(3)
if driver.current_url == "http://supportform.apple.com/201110/":
return False
self.login(driver)
# select state and continue
time.sleep(3)
self.submitState(driver)
# final submit
time.sleep(3)
driver.find_element_by_id("finalContinue").click()
return True
def newSN(self, serial, driver):
# select country and enter serialno
driver.get("http://supportform.apple.com/201110/")
self.setCountrySN(serial, driver)
# select state and continue
time.sleep(3)
if driver.current_url == "http://supportform.apple.com/201110/":
return False
self.submitState(driver)
# final submit
time.sleep(3)
driver.find_element_by_id("finalContinue").click()
return True
def automateSerials(self):
for i in self.serials:
if self.aloSuccess == False:
if not self.initiateSN(i, self.driver):
self.failedSerials.append(i)
del i
else:
self.aloSuccess = True
else:
if not self.newSN(i, self.driver):
self.failedSerials.append(i)
del i
self.driver.quit()
print(str(len(self.serials) - len(self.failedSerials)) + ":" + str(len(self.serials)))
def main():
newSet = SerialSet(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
newSet.parseSerialFile()
newSet.automateSerials()
if __name__ == "__main__":
main()
Error:
Traceback (most recent call last):
File "automate.py", line 90, in <module>
main()
File "automate.py", line 85, in main
newSet = SerialSet(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
File "automate.py", line 11, in __init__
self.driver = webdriver.Chrome(driverPath)
File "/Library/Python/2.7/site- packages/selenium/webdriver/chrome/webdriver.py", line 67, in __init__
desired_capabilities=desired_capabilities)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 90, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 177, in start_session
response = self.execute(Command.NEW_SESSION, capabilities)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 234, in execute
response = self.command_executor.execute(driver_command, params)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 401, in execute
return self._request(command_info[0], url, body=data)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 432, in _request
resp = self._conn.getresponse()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1132, in getresponse
response.begin()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 453, in begin
version, status, reason = self._read_status()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 417, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine: ''
Make sure your using the latest version chromedriver:
http://chromedriver.storage.googleapis.com/2.25/chromedriver_linux64.zip
I installed chromedriver 2.0 and got this error,
when I upgraded to 2.25 it got rid of this error.

WebDriver. Python. I want to store one of the option of drop-down menu by value as text, how to do it?

I want to store one of the option of drop-down menu by value as text. I select random option by next Python script:
#Random select option by value
assignJob = Select(driver.find_element_by_name('job[job_title]'))
jobValue = str(randint(1, 6))
assignJob.select_by_value(jobValue)
HTML code:
<select name="job[job_title]" class="formSelect valid" id="job_job_title">
<option value="" selected="selected">-- Select --</option>
<option value="1">Customer Service</option>
<option value="4">QA Engineer</option>
<option value="3">QA Manager</option>
<option value="2">SDET</option>
<option value="5">Software Developer</option>
<option value="6">Software Development Manager</option>
</select>
Error when I assign variable storedJob = driver.find_element_by_css_selector("#job_job_title option[value=jobValue]").text:
Traceback (most recent call last):
File "code.py", line 62, in <module>
storedJob = driver.find_element_by_css_selector("#job_job_title option[value
=jobValue]").text
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 365, in find_element_by_css_selector
return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 681, in find_element
{'using': by, 'value': value})['value']
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 164, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: u'no such element\n
(Session info: chrome=32.0.1700.102)\n (Driver info: chromedriver=2.8.241075,p
latform=Windows NT 6.1 SP1 x86)'
Code:
assignJob = Select(driver.find_element_by_name('job[job_title]'))
jobValue = str(randint(1, 6))
assignJob.select_by_value(jobValue)
storedJob = driver.find_element_by_css_selector("#job_job_title option[value=jobValue]").text
print storedJob
Another Error:
Traceback (most recent call last):
File "code.py", line 63, in <module>
storedJob = driver.find_element_by_css_selector(jobValueSelector).text
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 365, in find_element_by_css_selector
return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 681, in find_element
{'using': by, 'value': value})['value']
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 164, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriv
er\remote\errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidElementStateException: Message: u"invalid elem
ent state: Failed to execute query: '#job_job_title option[value=2]' is not a va
lid selector.\n (Session info: chrome=32.0.1700.102)\n (Driver info: chromedri
ver=2.8.241075,platform=Windows NT 6.1 SP1 x86)"
You could use a CSS selector, to locate that option and ask selenium to return its text.
driver.find_element_by_css_selector("#job_job_title option[value=2]").text
Replace 2 with the variable jobValue for you specific scenario.
EDIT
jobValue is a variable(str), you cannot directly pass a variable in Python.
jobValueSelector = "#job_job_title option[value='%s']" %jobValue
storedJob = driver.find_element_by_css_selector(jobValueSelector).text
print storedJob
The piece of code below is in Ruby.. I think Python and Ruby is almost the same.
select_list = driver.find_element(:id, 'job_job_title')
options = select_list.find_elements(:tag_name, 'option')
index = rand(1..options.count) # Get random number from index 1 to options.count
my_variable = options[index]
Let me try my skill in Python (not tested)! :)
select_list = driver.find_element_by_id("job_job_title")
options = select_list.find_elements_by_tag_name("option")
index = randint(1, len(options))
variable = options[index]

Categories