How can I .send_keys(v.S1) a variable? - python

I have only been programing or coding or whatever it is that I am doing for a few days and could use a hand figuring out what I need to research to figure out what I am trying to do. I am working on a project for charity so I dont really want to learn all kinds of things I will probably never use again so I was hoping someone could tell me how to do this or point me in the direction of what I need to learn to make this happen.
So I have created a crawler that goes and types text into a search bar, Eggs for example and then takes me to the eggs results and captures the data, brand, price, count ect.
searchBox.send_keys(v.S1)
My problem is I can not figure out how to change v.S1 into V.S2 so I can automate going thru many searches without having to copy an paste the code over and over again.
I am working with a main.py to call the functions, a functions.py to store the functions and a variables.py to store the list of variables as S1-S2-S3 ect.
I have been able to to get searchBox.send_keys(v.S1) to work as searchBox.send_keys(X) with a variable X = v.S1
but for the life of me I can not figure out how to add +1 to make X = v.S2 after the function completes the first search.
So far all the information I have needed has been under the same By.CLASS_NAME but I have set those to a variable as well since I may need to change some of those on a per case basis as I go as well.
Well any help or someone pointing me in the right direction would be appreciated. Thanks.

To pass a character sequence e.g. v.S1, v.S2, v.S3, etc you can use the range() function and use argument-unpacking operator i.e. * and finally append it to the constant string v.S
elements = [*range(1,6,1)]
elements = ['v.S{0}'.format(element) for element in elements]
print(elements)
# prints -> ['v.S1', 'v.S2', 'v.S3', 'v.S4', 'v.S5']

I suggest you to add all the S1,S2.... variables in a list or tuple and then iterate using a simple for loop like,
# varlist is a list containing all variables
for i in varlist:
searchBox.send_keys(i)

Related

best way to execute a list of instructions (n=0 to n=20). stop, then return to line n

i'm not sure I was very clear the first time I posted this, so i'll try agian.
thanks for bearing with me.
I have a program for a procedure, the procedure incurs like a drying time overnight.
(i'ts for my machine shop but work with me here)
it's like this:
a1=input('enter 1 after cutting paper')
a2=input('enter 1 after gluing paper')
a3=input('enter 1 after drying all night')
a4=input('enter 1 after resuming the next day')
i would just write down: "stopped on line a3".
and I was planning on writing a "for loop" to "unpack the list".
it was recommended to me that I use a dictionary rather than list; however I don't really see the difference, especially since a list can be enumerated, while a dictionary cannot.
I was thinking I could use a for loop and somehow run each ith value of the list.
thoughts anyone?
edit:
okay sorry for not explaining it well:
maybe this will help:
"i'm looking for a way to store information in a list, where the information is executable."
then I want to run that list starting on line n.
so like a recipe, but can start at any line.
You can define a list of actions:
actions = [
'cutting paper',
'gluing paper',
'drying all night',
'resuming the next day',
]
And then iterate through them:
for action in actions:
answer = input('input 1 after ' + f'{action}')
... but I still don't know what your actual question is. What do you mean by "stop"? Are you saying that you can't leave the computer running overnight, and you need some way to resume your progress in the list when the computer starts again the next morning?
I created the instructions on a separate .txt file. Then was able to index each step in the Py code. This works. I can also pass Py code through from the .txt document by adding a special character for the Py script to search for, then run the lines

Python: can a variable take two different strings?

Am I being dumb here?
I would like to know if I have a list called cons=['gps-ops', 'beidou'] and in my code there are different names for the same thing. i.e: 'gps-ops' = 'GPS' and 'beidou'='BDS'.
Some parts of the code (class) takes 'gps-ops' and some parts take 'GPS'. At the moment I have been using if and elif statements at different sections of the code.
Is there a way to say 'gps-ops' is also 'GPS' and vice versa, depending on how the user inputs the string throughout the code?
You could put every word for each valid name in a set like {'gps-ops', 'GPS'} and then go through your list in a for loop and check if that word is in the set:
gps_set = {'gps-ops', 'GPS'}
for name in cons:
if name in gps_set:
# do somehthing if true
Read the python docs for sets, they're quite an amazing data structure

Display text from a key/value pair in a nested dictionary

I'm a novice.
I am trying to print the elements from the Periodic Table to the screen arranged like the table itself. I'm using (' - ') to separate the symbols that I haven't written in the dictionary yet. I'm only using a nested dictionary with two entries total to minimize confusion.
Training Source last exercise.
I asked this question elsewhere and someone (correctly) suggested using str.join(list) but It wasn't part of the tutorial.
I'm trying to teach myself and I want to understand. No schooling, no work, no instructor.
The hints at the bottom of the linked tutorial says:
1."Use a for loop to loop through each element. Pick out the elements' row numbers and column numbers."
2."Use two nested for loops to print either an element's symbol or a series of spaces, depending on how full that row is."
I'd like to solve it this way. Thanks in advance.
Note* No, pre-intermediate, intermediate or advanced code please, the tutorial has only covered code related to variables, strings, numbers, lists, tuples, functions(beginners),if statements, while loops, basic terminal apps and dictionaries.
Lastly I'd like to have the table itself printed with the shape of the real Periodic Table. If you could throw in a bit of that code for a novice it'd really help thanks.
My attempt(wrong):
ptable = {'mercury':{'symbol':'hg','atomic number': '80','row': '6','column': '12','weight':'200.59',}, 'tungsten':{'symbol':'w','atomic number':'74','row':'6','column':'6','weight':'183.84'},}
for line in range(1,7):
for key in ptable:
row = int(ptable[key]['row'])
column = int(ptable[key]['column'])
if line != row:
print('-'*18)
else:
space = 18 - column
print('-'*(column-1)+ptable[key]['symbol']+'-'*space)
outputs:
------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
------------------
-----------hg------
-----w------------
The output should have 7 lines as in the Periodic table. It is supposed to display the symbols of each element in the correct place as in the Periodic Table. Since I only have two elements in the library it should show Hg and W in their correct places
The experienced programmers' solution:
for line in range(1, 8): # line will count from 1 to 7
# display represents the line of elements we will print later
# hyphens show that the space is empty
# so we fill the list with hyphens at first
display = ['-'] * 18
for key in ptable:
if int(ptable[key]['row']) == line:
# if our element is on this line
# add that element to our list
display[int(ptable[key]['column']) - 1] = ptable[key]['symbol']
# str.join(list) will "join" the elements of your list into a new string
# the string you call it on will go in between all of your elements
print(''.join(display))
I honestly think this code isn't that hard to understand and I think trying to change it would only make it more complicated. I'm going to put you some links at the end for you to check it out and understand the ''join() method and the range() function which you seem not to understand either. You said you wanted to learn Python by yourself and that's a great thing! (I'm doing it too) But that doesn't mean you have to stick to a tutorial ;). You can go beyond it and also skip the parts you don't care about and come back later when you need them. If you need explanations about methods (like ''.join) or any other thing let me know. Sorry if that doesn't help you ;(.
Links:
The .join() method
The range() function

I have a python tuple of namedtuples. Is there a way to access individual members other than by indexing or unpacking them?

I have a python 3.5 tuple where a typical structure of a data item is something like this.
item = (PosixPath('/mnt/dson/Music/iTunes/iTunes Music/funtoons.mp3'), tagtypes(txt=False, word=False, ebook=False, image=False, exe=False, iso=False, zip=False, raw=False, audio=True, music=True, photoshop=False, video=False, src=False, geek=False, pdf=False, appledouble=False, dot=False), fileinfo(size=13229145, datetime=1333848240.0))
This describes a common file on my Linux filesystem. If I want to know the size
of the given file, I can access it with something like this ---
item[2].size. Similarly, logic to grab the tags describing the file's contents would use code like --- item[1].music, etc..
It seems on the face of it, with each object being unique in the tuple
that if you wanted to access one of the members, you should be able to
drill down in the tuple and do something like item.fileinfo.size. All of
the information to select the correct item from the tuple is deducible
to the interpreter. However, if you do attempt something like
item.fileinfo.size you will get (almost expectedly) an attribute error.
I could create a namedtuple of namedtuples but that has a bit of a code smell to it.
I'm wondering if there is a more pythonic way to access the members of the tuple other than by indexing or unpacking. Is there some kind of
shorthand notation such that you convey to the interpreter which one of
the tuple's elements you must be referencing (because none of the other
options will fit the pattern)?
This is kind of a hard thing to explain and I'm famous for leaving out
critical parts. So if more info is needed by the first responders, please
let me know and I'll try and describe the idea more fully.
You really think doing this:
Item = namedtuple('Item', 'PosixPath tagtypes fileinfo')
item = Item(PosixPath('/mnt/dson/Music/iTunes/iTunes Music/funtoons.mp3'), tagtypes(txt=False, word=False, ebook=False, image=False, exe=False, iso=False, zip=False, raw=False, audio=True, music=True, photoshop=False, video=False, src=False, geek=False, pdf=False, appledouble=False, dot=False), fileinfo(size=13229145, datetime=1333848240.0))
is not worth it if it lets you do item.fileinfo.size AND item[2].size ? That's pretty clean. It avoids creating classes by hand and gives you all the functionality in a clear and concise manner. Seems like pretty good python to me.

How to create a function in Python that makes objects (i.e lists)

I couldn't find a guide that would help me out in this area. So I was hoping somebody could help me explain this kind of programming in Python. I am trying to write a code that goes something like this:
def Runner():
for G in range(someRange):
makeListObjectcalled 'ListNumber'+'G'
ListNumberg.append(G*500000 or whatever)
print ListNumberG
#so I would have a someRange amount of lists
#named 0,1,2,3...(up to someRange) I could look through
I think it can be done with classes (in fact I'm guessing thats what they're for...) but I'm not sure. Could someone lay me down some clarifications please?
It looks like what you really want is a list of lists.
def Runner():
Lists = []
for G in range(someRange):
Lists[G] = []
Lists[G].append(G*500000 or whatever)
print Lists[G]
#This way, you have Lists[0], Lists[1], ..., Lists[someRange]
You want to dynamically create variables of type lists that store an array of values.
An easier and better approach (than juggling unknown variable names) is to use a dictionary to keep your lists in, so you can look them up by name/key:
(pseudo code, don't have my Python interpreter with me)
# create a dictionary to store your ListNumberG's
dict_of_lists = {}
# down the line in your loop, add each generated list to the dict:
dict_of_lists['ListNumberG'] = ListNumberG
Later you can find a list by it's name/key via
print(dict_of_lists['ListNumberG'])
or loop through them
for idx in range(bestguess):
print(dict_of_lists['ListNumber%s' % (idx,)])

Categories

Resources