I've been trying to test out this google form filler but keep running into an issue with the submit button. This has never happened before and I am not sure why, every time I run the code it fills in all the boxes, however, it sometimes doesn't fill out the gender question and rarely or never hits submit or submit another response. The google form link is in the code below.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import random
from time import sleep
from random import randint
import random
s=Service('/Users) #have the current service installed here
driver = webdriver.Chrome(service=s)
url="https://forms.gle/sNCNuebKtpdF6j7t6"
driver.get(url)
datas = [
]
for i in range(10):
sampleList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
val1 = random.choices(sampleList, weights=(5.8, 6.72, 7.5, 7.24, 6.8, 3.16, 3.5, 4.5, 1.2, 2.3), k=10) # 25,25,50
val2 = random.choices(sampleList, weights=(5.8, 6.7, 7.5, 7.2, 6.83, 9.1, 9.5, 8.5, 8.2, 8.3), k=10) # 25,25,50
val3 = random.choices(sampleList, weights=(5.8, 6.7, 7.52, 7.2, 6.8, 3.1, 4.5, 3.53, 1.2, 0.3), k=10) # 25,25,50
val4 = random.choices(sampleList, weights=(0.8, 2.7, 3.53, 3.2, 5.8, 4.12, 9.5, 9.5, 9.2, 9.3), k=10) # 25,25,50
val5 = random.choices(sampleList, weights=(1.78, 3.7, 5.5, 3.2, 6.8, 5.1, 9.51, 8.5, 8.2, 9.3), k=10) # 25,25,50
valx = random.randint(0,9)
datas.append([val1[valx],val2[valx],val3[valx],val4[valx],val5[valx]]) #this list prints out alright and gets the values needed
radiobuttons = driver.find_elements(By.CLASS_NAME, "appsMaterialWizToggleRadiogroupElContainer")
print(datas)
for data in datas: #for each mini list in the big list
print(data)
radiolist = [0, 1, 2, 3]
val0 = random.choices(radiolist, weights=(9.8,11.5,1.2,1.8), k=10)
print(val0)
rand = random.randint(0,9)
print(rand)
#radiobuttons[val0[rand]].click()
radiobuttons[1].click()
print(radiobuttons[val0[rand]])
count = 0 #count is 0
# contain input boxes
textboxes = driver.find_elements(By.CLASS_NAME, 'quantumWizTextinputPaperinputInput') #these textboxes and elements seem to work and get filled out
for value in textboxes:
# enter value
value.send_keys(data[count])
print(value)
# increment count value
count += 1
submit = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[class*='appsMaterialWizButtonPaperbuttonContent ']"))).click() #this sometimes works but if so only once
# fill another response
print('hi')
another_response = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Submit another response'))).click()
#this does not work at all
#textboxes = browser.find_elements_by_class_name("quantumWizTextinputPaperinputInput")
#radiobuttons = browser.find_elements_by_class_name("docssharedWizToggleLabeledLabelWrapper")
#checkboxes = browser.find_elements_by_class_name("quantumWizTogglePapercheckboxInnerBox")
#submitbutton = browser.find_element_by_class_name("appsMaterialWizButtonPaperbuttonContent")
# close the window
driver.close()
url="https://forms.gle/sNCNuebKtpdF6j7t6"
driver.get(url)
datas = []
for i in range(10):
sampleList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
val1 = random.choices(sampleList, weights=(5.8, 6.72, 7.5, 7.24, 6.8, 3.16, 3.5, 4.5, 1.2, 2.3), k=10) # 25,25,50
val2 = random.choices(sampleList, weights=(5.8, 6.7, 7.5, 7.2, 6.83, 9.1, 9.5, 8.5, 8.2, 8.3), k=10) # 25,25,50
val3 = random.choices(sampleList, weights=(5.8, 6.7, 7.52, 7.2, 6.8, 3.1, 4.5, 3.53, 1.2, 0.3), k=10) # 25,25,50
val4 = random.choices(sampleList, weights=(0.8, 2.7, 3.53, 3.2, 5.8, 4.12, 9.5, 9.5, 9.2, 9.3), k=10) # 25,25,50
val5 = random.choices(sampleList, weights=(1.78, 3.7, 5.5, 3.2, 6.8, 5.1, 9.51, 8.5, 8.2, 9.3), k=10) # 25,25,50
valx = random.randint(0,9)
datas.append([val1[valx],val2[valx],val3[valx],val4[valx],val5[valx]]) #this list prints out alright and gets the values needed
print(datas)
for data in datas: #for each mini list in the big list
radiobuttons = driver.find_elements(By.CLASS_NAME, "appsMaterialWizToggleRadiogroupElContainer")
print(data)
radiolist = [0, 1, 2, 3]
val0 = random.choices(radiolist, weights=(9.8,11.5,1.2,1.8), k=10)
print(val0)
rand = random.randint(0,9)
print(rand)
#radiobuttons[val0[rand]].click()
radiobuttons[1].click()
print(radiobuttons[val0[rand]])
count = 0 #count is 0
# contain input boxes
textboxes = driver.find_elements(By.CLASS_NAME, 'quantumWizTextinputPaperinputInput') #these textboxes and elements seem to work and get filled out
for value in textboxes:
# enter value
value.send_keys(data[count])
print(value)
# increment count value
count += 1
try:
submit = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Submit']")))
submit.click() #this sometimes works but if so only once
except Exception as e:
print(str(e))
# fill another response
print('hi')
try:
another_response = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Submit another response')))
another_response.click()
except Exception as e:
print(str(e))
Your issues were in the radiobuttons as you need to regrab that element every loop due to page redirection so you ended up with stale elements and using the wrong selector for the submit button. With the following fixes it runs.
Related
Hi I have this calculation but I am failing to understand how this line [array([1050885., 1068309., 1085733., 1103157., 1120581.]) of the output is calculated, please explain.
creating sample data:
#creating sample data:
data1 = pd.DataFrame({"client": ['x1', 'x2'],
"cat": ['Bb', 'Ee'],
"amt": [1000,300],
"time":[2, 3],
"group":[10, 25]})
listc = ['Aa','Bb','Cc','Dd','Ee']
val1 = pd.DataFrame({'time': [1, 2, 3],
'lim %': [0.1, 0.11, 0.112]})
val2 = pd.concat([pd.DataFrame({'group':g, 'perc': 0.99, 'time':range(1, 11)}
for g in data1['group'].unique())]).explode('time')
mat = np.arange(75).reshape(3,5,5)
vals = [val1, val2]
data1['cat'] = pd.Categorical(data1['cat'],
categories=listc,
ordered=True).codes
for i in range(len(vals)):
if 'group' in vals[i].columns:
vals[i] = vals[i].set_index(['time', 'group'])
else:
vals[i] = vals[i].set_index(['time'])
#nested loop calculation
calc = {}
for client, cat, amt, start, group in data1.itertuples(name=None, index=False):
for time in range(start, len(mat)+1):
if time == start:
calc[client] = [[amt * mat[time-1, cat, :]]]
else:
calc[client].append([calc[client][-1][-1] # mat[time-1]])
for valcal in vals:
if isinstance(valcal.index, pd.MultiIndex):
value = valcal.loc[(time, group)].iat[0]
else:
value = valcal.loc[time].iat[0]
calc[client][-1].append(value * calc[client][-1][-1])
output:
{'x1': [[array([30000, 31000, 32000, 33000, 34000]),
array([3300., 3410., 3520., 3630., 3740.]),
array([3267. , 3375.9, 3484.8, 3593.7, 3702.6])],
[array([1050885., 1068309., 1085733., 1103157., 1120581.]), #how is this line calculated?
array([117699.12 , 119650.608, 121602.096, 123553.584, 125505.072]),
array([116522.1288 , 118454.10192, 120386.07504, 122318.04816,
124250.02128])]],
'x2': [[array([21000, 21300, 21600, 21900, 22200]),
array([2352. , 2385.6, 2419.2, 2452.8, 2486.4]),
array([2328.48 , 2361.744, 2395.008, 2428.272, 2461.536])]]}
what I need the calc for this line to be is:
[array([1050885., 1068309., 1085733., 1103157., 1120581.])
it should take array([3267. , 3375.9, 3484.8, 3593.7, 3702.6])] multiplied by mat at time 3, how can I get it to do this?
I was wondering how I could take this user input(below) and just modify the item that is already in the list. If the user does not input the same item as show in the list then just add the input as a new grocery item.
List
inventory = [['Milk, 3.99, 25'],
['Bread, 1.99, 35'],
['Eggs, 1.99, 50'],
['Flour, 0.52, 20'],
['Rice, 0.72, 35']]
Input
modItem = input("Enter the name of an existing item you want to modify:")
modPrice = input("Enter the new price of the item:")
modStock = input("Enter the new stock of the item:")
inventory.append([modItem, modPrice, modStock])
Try to check if the item already exists using a simple function:
def check_inventory(modItem, inventory):
try:
for item in inventory:
if modItem == item[0].split(', ')[0]:
return True
except:
pass
return False
...
# then, you can call your function
if (check_inventory(modItem, inventory)):
inventory.append([modItem, modPrice, modStock])
The second approach is converting your list into a dict. I would recommend this.
You could use a dict
inventory = {'Milk': [3.99, 25],
'Bread': [1.99, 35],
'Eggs': [1.99, 50],
'Flour': [0.52, 20],
'Rice': [0.72, 35]}
modItem = input("Enter the name of an existing item you want to modify:")
modPrice = float(input("Enter the new price of the item:"))
modStock = int(input("Enter the new stock of the item:"))
Enter the name of an existing item you want to modify:Milk
Enter the new price of the item:10
Enter the new stock of the item:12
If item already exists, it will be replaced, else a new key-value pair would be added
inventory[modItem] = [modPrice, modStock]
inventory
{'Milk': [10.0, 12],
'Bread': [1.99, 35],
'Eggs': [1.99, 50],
'Flour': [0.52, 20],
'Rice': [0.72, 35]}
Your inventory list was malformed. Here's code that does what you want in the most direct way, given your existing code and the corrected version of your data:
inventory = [['Milk', '3.99', '25'],
['Bread', '1.99', '35'],
['Eggs', '1.99', '50'],
['Flour', '0.52', '20'],
['Rice', '0.72', '35']]
modItem = input("Enter the name of an existing item you want to modify:")
modPrice = input("Enter the new price of the item:")
modStock = input("Enter the new stock of the item:")
for item in inventory:
if item[0] == modItem:
item[1] = modPrice
item[2] = modStock
break
else:
inventory.append([modItem, modPrice, modStock])
This code loops over the existing inventory, looking for the item the user entered the name of. If the name is found, the item containing that item is updated with the new price and quantity. If no existing item is found, then a new item is created and added.
You could use enumerate and modify the list while iterating over the elements:
inventory = [['Milk, 3.99, 25'],
['Bread, 1.99, 35'],
['Eggs, 1.99, 50'],
['Flour, 0.52, 20'],
['Rice, 0.72, 35']]
modItem = 'Milk'
modPrice = 4
modStock = 30
found = False
for idx, elt in enumerate(inventory):
if modItem in elt[0]:
inventory[idx] = [f"{modItem}, {modPrice}, {modStock}"] # modify the element at the found index
found = True
break
if not found:
inventory.append([f"{modItem}, {modPrice}, {modStock}"])
print(inventory)
Output:
[['Milk, 4, 30'], ['Bread, 1.99, 35'], ['Eggs, 1.99, 50'], ['Flour, 0.52, 20'], ['Rice, 0.72, 35']]
Further, I would suggest to keep the inner list as the list of elements. Currently, it is just a single element with a str object.
inventory = [['Milk', 3.99, 25],
['Bread', 1.99, 35],
['Eggs', 1.99, 50],
['Flour', 0.52, 20],
['Rice', 0.72, 35]]
found = False
for idx, elt in enumerate(inventory):
if modItem == elt[0]:
inventory[idx] = [modItem, modPrice, modStock]
found = True
break
if not found:
inventory.append([modItem, modPrice, modStock])
print(inventory)
Output:
[['Milk', 4, 30], ['Bread', 1.99, 35], ['Eggs', 1.99, 50], ['Flour', 0.52, 20], ['Rice', 0.72, 35]]
I would like to calculate the maximum of 3 columns value.
import pandas as pd
import pandas_datareader.data as web
data = web.DataReader("^NSEI" , data_source="yahoo",start = "1/4/2016",end ="6/4/2018")
data=pd.DataFrame(data)
data["High-Low"] = data["High"] - data["Low"]
data["Close-low"] = abs(data["Close"].shift(1) - data["Low"])
data["Close-High"] = abs(data["Close"].shift(1) - data["High"])
data["True_Range"] = data[[data["High-Low"], data["Close-low"],data["Close-High"]]].max(axis=1)
In data["True _Range"] column, I want to take the maximum of value in data["High-low"],data["Close-low"] and data["Close-high"] columns. On this, it is giving a name error.
KeyError: "None of [Index([(156.44970703125, 67.9501953125, 79.75, 118.35009765625, 53.05029296875, 110.75, 100.5, 165.150390625, 161.0, 139.2001953125, 127.25, 98.60009765625, 229.39990234375, 148.7001953125, 105.7998046875, 65.94970703125, 58.19970703125, 59.25, 172.85009765625, 59.2001953125, 148.25, 69.10009765625, 91.099609375, 96.5, 149.349609375, 48.30029296875, 94.10009765625, 248.69970703125, 165.7998046875, 126.0, 166.94970703125, 163.05029296875, 87.25, 80.89990234375, 51.69970703125, 151.0, 81.0498046875, 72.80029296875, 67.7998046875, 268.80029296875, 200.39990234375, 72.2001953125, 77.900390625, 61.7998046875, 85.0, 114.7001953125, 99.7001953125, 83.35009765625, 68.650390625, 92.400390625, 102.85009765625, 105.89990234375, 95.7001953125, 95.849609375, 84.400390625, 56.25, 161.69970703125, 70.64990234375, 98.5, 75.60009765625, 74.0498046875, 60.05029296875, 147.64990234375, 46.89990234375, 94.89990234375, 42.64990234375, 161.94970703125, 54.0498046875, 92.599609375, 77.85009765625, 72.85009765625, 94.35009765625, 50.0, 84.0, 151.9501953125, 50.4501953125, 157.5498046875, 100.349609375, 52.5, 155.10009765625, 51.75, 70.69970703125, 60.5498046875, 120.10009765625, 59.19970703125, 112.2001953125, 66.39990234375, 96.7998046875, 101.75, 60.39990234375, 71.2998046875, 109.400390625, 76.64990234375, 98.39990234375, 45.75, 131.900390625, 134.5, 87.150390625, 49.2001953125, 79.2998046875, ...), (nan, 28.0498046875, 63.44970703125, 184.39990234375, 12.75, 107.0, 76.05029296875, 84.5, 118.60009765625, 109.5, 101.39990234375, 13.14990234375, 193.60009765625, 59.2998046875, 50.80029296875, 1.25, 16.44970703125, 28.14990234375, 21.85009765625, 22.2998046875, 127.900390625, 105.25, 4.150390625, 2.64990234375, 125.89990234375, 112.10009765625, 120.4501953125, 255.75, 107.35009765625, 75.849609375, 125.25, 87.60009765625, 19.39990234375, 45.7998046875, 10.0498046875, 143.849609375, 99.7998046875, 57.30029296875, 14.5, 203.9501953125, 48.05029296875, 85.85009765625, 37.19970703125, 31.5, 43.2001953125, 61.0, 84.39990234375, 25.5498046875, 4.849609375, 85.9501953125, 55.4501953125, 19.35009765625, 5.35009765625, 13.35009765625, 60.4501953125, 44.2998046875, 128.7998046875, 32.85009765625, 46.4501953125, 33.2001953125, 72.2998046875, 8.64990234375, 170.14990234375, 11.4501953125, 78.5, 19.75, 38.35009765625, 8.0498046875, 63.25, 7.7001953125, 37.150390625, 30.64990234375, 38.69970703125, 72.2998046875, 32.5, 22.10009765625, 145.44970703125, 58.5498046875, 72.5, 70.75, 49.75, 0.30029296875, 57.14990234375, 20.099609375, 28.349609375, 106.89990234375, 0.7998046875, 116.19970703125, 42.75, 18.9501953125, 80.0, 103.35009765625, 47.64990234375, 27.5, 15.25, 60.44970703125, 13.60009765625, 7.39990234375, 5.85009765625, 44.2001953125, ...)], dtype='object')] are in the [columns]"
Try:
data["True_Range"] = data[["High-Low","Close-low","Close-High"]].max(axis=1)
Instead of:
data["True_Range"] = data[[data["High-Low"], data["Close-low"],data["Close-High"]]].max(axis=1)
Your error signifies that you have input the data instead of the nested columnnames into your view of the dataframe, which produced the error.
Since the data from the columns themselves are not in the columnnames - you received the error.
One way of avoiding the error is:
data["True_Range"] = data[["High-Low", "Close-low", "Close-High"]].max(axis=1)
I'm trying to cycle through 2 lists using for loops to calculate the sum for each unique reference. I suppose I'm looking for a pythonic sumif!
# list of data ("user_ID", "contract_Number", "weight", "type")
list1 = [
('1','261','6.2','Input'),
('1','262','7.2','Input'),
('1','263','5.2','Input'),
('1','264','8.2','Input'),
('1','261','3.2','Input'),
('1','262','2.2','Input'),
('1','262','7.2','Input'),
('1','263','4.2','Input'),
('1','264','6.2','Input'),
('1','265','6.2','Input'),
('1','261','9.2','Input'),
('1','261','10.2','Input')
]
contract_list = []
# create a list of contract numbers
for data_row in list1:
if data_row[0] == "1" and data_row[3] == "Input":
contract_list.append(data_row[1])
#remove duplication - left with a list of unique contract numbers
contract_list = list(dict.fromkeys(contract_list))
print(contract_list)
# I'm trying this...[28.6, 16.6, 9.4, 14.4, 6.2]
tally_list = []
tally = 0
for c in contract_list:
for l in list1:
if data_row[0] == '1' and data_row[1] == contract_list[0]:
tally = tally + float(data_row[2])
tally_list.append(tally)
print(tally_list)
I'm expecting...
['261', '262', '263', '264', '265']
[28.6, 16.6, 9.4, 14.4, 6.2]
I'm getting...
['261', '262', '263', '264', '265']
[122.40000000000002, 244.7999999999999, 367.19999999999976, 489.5999999999996, 612.0]
# I'm trying this...[28.6, 16.6, 9.4, 14.4, 6.2]
tally_list = []
tally = 0
for c in contract_list:
for l in list1: #<----------
if data_row[0] == '1' and data_row[1] == contract_list[0]:
tally = tally + float(data_row[2])
tally_list.append(tally)
In the marked row, it looks like you want to use the data_row variable instead of l
Actually, try this, you need to additionally reset tally and also use c instead of contract_list[0] in the final if statement.
# I'm trying this...[28.6, 16.6, 9.4, 14.4, 6.2]
tally_list = []
tally = 0
for c in contract_list:
for data_row in list1:
if data_row[0] == '1' and data_row[1] == c: #<----
tally = tally + float(data_row[2])
tally_list.append(tally)
tally=0 #<---
print(tally_list)
Just another approach using a defaultdict
from collections import defaultdict
list1 = [
('1','261','6.2','Input'),
('1','262','7.2','Input'),
('1','263','5.2','Input'),
('1','264','8.2','Input'),
('1','261','3.2','Input'),
('1','262','2.2','Input'),
('1','262','7.2','Input'),
('1','263','4.2','Input'),
('1','264','6.2','Input'),
('1','265','6.2','Input'),
('1','261','9.2','Input'),
('1','261','10.2','Input')
]
d = defaultdict(int)
for tup in list1:
if tup[0] == '1' and tup[3] == 'Input':
d[tup[1]] += float(tup[2])
contract_list = list(d)
print(contract_list)
tally_list = [format(v, '.1f') for v in d.values()]
print(tally_list)
Output:
['261', '262', '263', '264', '265']
['28.8', '16.6', '9.4', '14.4', '6.2']
I'm trying to input a csv file that I can then use to do calculations:
import csv
data=[]
file=input ("Enter file name: ")
with open(file,"r") as f:
reader=csv.reader(f)
for row in reader:
data.append([x.strip(";") for x in row])
print(data)
print("Calculate COV")
lst= data
spl= [x.split(";") for y in lst for x in y]
flattened = [float(x) for y in spl for x in y if x]
print (flattened)
But I keep getting this when I use decimal numbers:
[['13', '25;12', '97;13', '12;13', '47;13', '44;13', '09;12', '86;12', '78;12', '91;12', '93;12', '91;13', '11'], ['12', '92;13', '42;13', '58;13', '7;13', '62;13', '7;13', '31;12', '86;12', '59;12', '81;13', '46;12', '9'], ['13', '39;13', '5;13', '29;13', '26;13', '38;13', '45;13', '46;11', '95;12;12', '57;13', '22;12', '88'], ['12', '48;13', '76;13', '7;13', '77;13', '08;13', '48;13', '25;12', '31;12', '56;12', '56;12', '95;13', '38'], ['12', '52;14', '07;14', '46;14', '13;13', '98;14', '07;13', '92;12', '7;13', '01;12', '79;13;13', '13']]
When I should have this:
[13.25, 12.97, 13.12, 13.47, 13.44, 13.09, 12.86, 12.78, 12.91, 12.93, 12.91, 13.11, 12.92, 13.42, 13.58, 13.7, 13.62, 13.7, 13.31, 12.86, 12.59, 12.81, 13.46, 12.9, 13.39, 13.5, 13.29, 13.26, 13.38, 13.45, 13.46, 11.95, 12.57, 13.22, 12.88, 12.48, 13.76, 13.7, 13.77, 13.08, 13.48, 13.25, 12.31, 12.56, 12.56, 12.95, 13.38, 12.52, 14.07, 14.46, 14.13, 13.98, 14.07, 13.92, 12.7, 13.01, 12.79, 13.0, 13.13]
It's really not clear how you are trying to use the CSV module. First, by default, the csv module is going to use comma separated values, not semicolon separated values.
But either way, let's try writing some code:
import csv
class MyDialect(csv.excel):
delimiter = ';'
with open('in.csv', 'r') as f:
reader = csv.reader(f, MyDialect())
data = list(reader)
data = [[float(elem.replace(',', '.')) for elem in line] for line in data]
for line in data:
print line
in.csv
13,25;12,97;13,12;13,47;13,44;13,09;12,86;12,78;12,91;12,93;12,91;13,11
12,92;13,42;13,58;13,7;13,62;13,7;13,31;12,86;12,59;12,81;13,46;12,9
13,39;13,5;13,29;13,26;13,38;13,45;13,46;11,95;12;12,57;13,22;12,88
12,48;13,76;13,7;13,77;13,08;13,48;13,25;12,31;12,56;12,56;12,95;13,38
12,52;14,07;14,46;14,13;13,98;14,07;13,92;12,7;13,01;12,79;13;13,13
stdout
[13.25, 12.97, 13.12, 13.47, 13.44, 13.09, 12.86, 12.78, 12.91, 12.93, 12.91, 13.11]
[12.92, 13.42, 13.58, 13.7, 13.62, 13.7, 13.31, 12.86, 12.59, 12.81, 13.46, 12.9]
[13.39, 13.5, 13.29, 13.26, 13.38, 13.45, 13.46, 11.95, 12.0, 12.57, 13.22, 12.88]
[12.48, 13.76, 13.7, 13.77, 13.08, 13.48, 13.25, 12.31, 12.56, 12.56, 12.95, 13.38]
[12.52, 14.07, 14.46, 14.13, 13.98, 14.07, 13.92, 12.7, 13.01, 12.79, 13.0, 13.13]
Try this:
import csv
data=[]
import re
with open("out.csv","r") as f:
reader=csv.reader(f,delimiter=";")
for row in reader:
print row
data+=[x.split(",") for x in row]
print(data)
print("Calculate COV")
flattened = [float(x) for y in data for x in y]