If certain thing is included in input use anything after it - python-3.x

Hello I am currently working on a script that goes onto a website and automatically adds an Item to cart and purchases it for you I have a script that works except the only problem is that It is only able to checkout a single Item Item. Here is an example fo the script:
Item_code = input('Item code: ')
Size = input('Size: ')
def BOT():
driver = webdriver.Chrome(executable path=
URL = .....
driver.get(URL)
while True:
try:
driver.find_element_by_css_selector(Item_code).click()
break
except NoSuchElementException:
driver.refresh()
select = Select(driver.find_element_by_id('s'))
select.select_by_visible_text(Size)
The script finds the item with the item code that I use and then selects the size from the users choice
I want to be able to write the code and the size but If I want to bot to cart two Items in different sizes I want it to type in a , and insert the next Item code and Size For example:
12345, 6789
Large, Medium
I want to somehow write that if a comma is included to read and use the code after it after it uses the first one and repeat that for every comma so If I wanted to get 3 or even 4 all I would have to do is this:
1234, 5678, 7890, etc...
Large, medium, Small, etc...
If anyone could Help me out I would really appreciate it I was thinking of something like
for , in BOT():
(something like this but Im not sure )
I know how to tell the script that if Item_code == (',') then do this but that would not work because it needs to be just the comma and I do not know how to tell it to repeat the BOT() a second time and use the second code and size
If someone could help me out I would really appreciate it thanks.
(I want to be able to share this bot since I have already made a GUI for it and all that)
(not sure if the executable path will work when sharing)

I have fixed this problem I created several custom functions and called them on special if statements
ex.
if Item.count(',') == (1):
Cart1()
Checkout()
etc.....

Related

Removing an index number from a list/csv using input

i'm doing an exercise for school where you use python to store client details in a csv and i'm having trouble with adding a way for the user to delete their client details as pop won't accept anything but an index number - can someone help me find a way to do this? I'm really new to coding sorry.
Here's my code:
if first_name in name:
for x in range(0,len(existing_clients)):
if first_name == existing_clients[x][0]:
print(existing_clients[x])
index = existing_clients.index(existing_clients[x])
print(index)
existing_clients.pop(index)
The above works to print out the index number but I don't know how to make it delete the client details from the list/csv. I feel like i'm missing something really obvious and stupid.
Here's an example of the csv data making up existing_clients:
Ave,O' Hogan,Ms,Male,13/04/2022,Help Desk Operator,1285.66,64.80
Ariel,Fidge,Honorable,Female,15/09/2022,VP Quality Control,8.27,82.63
Timoteo,McGowing,Dr,Male,03/12/2021,General Manager,1751.11,23.92
Lezley,Wilmott,Mr,Male,04/07/2022,Statistician I,350.05,74.83

want to optimize a "phone number generator" code with loop deduction

Description of program:
1.makes unique random phone numbers based on how many you want it to i mean: if you pass 100 it makes 100 phone numbers.
2.creates text files based on the range you pass to it, i mean: if you need 100 text files containing 100 unique phone numbers either unique comparing to each number within or the other to be made forthcoming text files.
meanwhile it creates phone numbers sorts the phone numbers like below if it makes sense:
This format to expect in the text files :
1909911304
1987237347
........... and so on.............
This is the method responsible to do so:
(Note: I use make_numbers method as construction of operation, Actually num_doc_amount should be used.)
def make_numbers(self):
"""dont use this method:this method supports num_doc_amount method"""
# sorry for this amount of loops it was inevitable to make the code work
for number_of_files in range(self.amount_numbs):
# this loop maintains the pi_digits.txt making(txt)
number_of_files += 1
if number_of_files == self.amount_files:
sys.exit()
for phone_numbers in range(self.amount_numbs):
# This loop maintains the amount of phone numbers in each pi_digits.txt
file = open(f"{self.directory}\\{number_of_files}.{self.format}", 'w')
for numbers in range(self.amount_numbs):
# This loop is parallel to the previous one and
# writes that each number is which one from the
# whole amount of numbers
file.write(f"{numbers + 1}. - {self.first_fourz}{choice(nums)}"
f"{choice(nums)}{choice(nums)}{choice(nums)}"
f"{choice(nums)}{choice(nums)}{choice(nums)}\n")
def num_doc_amount(self):
"""first make an instance and then you can use this method."""
os.mkdir(f"{self.directory}") # makes the folder
for num_of_txt_files in range(self.amount_files):
# This loop is for number of text files.
num_of_txt_files += 1
self.make_numbers()
Note That:
1.The only problem i have is with those parallel loops going with each other, i don't know if i can make the code simplified.(please let me know if it can be simplified.)
2.The code works and has no error.
if there is any way to make this code simplified please help me.Thank you.
1.The only problem i have is with those parallel loops going with each other, i don't know if i can make the code simplified.(please let me know if it can be simplified.)
Even if that's not the only problem, indeed there are unnecessarily many loops in the above code. It takes not more than two: one loop over the files, one loop over the numbers; see below.
2.The code works and has no error.
That's false, since you want all the phone numbers to be unique. As said, the code has no provision that the written phone numbers are unique. To achieve this, it's easiest to generate all unique numbers once at the start.
def num_doc_amount(self):
"""first make an instance and then you can use this method."""
os.mkdir(self.directory) # makes the folder
un = sample(range(10**7), self.amount_files*self.amount_numbs) # all the unique numbers
# This loop is for number of text files:
for num_of_txt_file in range(self.amount_files):
with open("%s/%s.%s"%(self.directory, 1+num_of_txt_file, self.format), 'w') as file:
# This loop maintains the amount of phone numbers in each .txt:
for number in range(self.amount_numbs):
# writes one number from the whole amount of numbers
file.write("%s. - %s%07d\n" %(1+number, self.first_fourz, un.pop()))

Get a Steam key from a txt file then move it to another

I'm currently working on a Steam bot project that trades Steam items for Game keys. I'm already done with all the trading part, and the only part missing now is the part where the script actually looks for a key in my txt file. (one key per line)
I have a variable ready called totalKeyWeGive that outputs 1 , 2 , 3 etc depending on how many keys is the user buying.
So now I want to 1. get 1 , 2 , 3 etc keys from my file, then move these used keys to another file.
How can I do that ?
this is the part that I need to modify (everything is working) :
offer.accept(offer);
console.log("OFFER ACCEPTED");
//loop on how much we give the key
//get steamkey from file here ------
}
var textMsg = "Hello ! You bought "+totalKeyWeGive+ " Game keys. Your keys are: "
}
client.chatMessage(offer.partner.getSteamID64(), textMsg);
Thanks to everyone who will take the time to read this post. It's kinda messy, sorry about that :/
Not sure how the keys are organized in the txt file, but assuming they are one per line you could do something like this: https://stackoverflow.com/a/38843461/4686055
That is, before removing the line, save it in memory and write it to the target file.
Send an interval to slice() to remove multiple lines. Check this out for an example of how it works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Hope this helps!
Update: an alternative approach could be to use the readlines module instead of reading the entire file into memory: https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line

Selenium - find element by link text

I am using selenium webdriver on Chrome; python 3 on Windows 10.
I want to scrape some reports from a database. I search with a company ID and a year, the results are a list of links formatted in a specific way: something like year_companyID_seeminglyRandomDateAndDoctype.extension, e.g. 2018_2330_20020713F04.pdf. I want to get all pdfs of a certain doctype. I can grab all links for a certain doctype using webdriver.find_elements_by_partial_link_text('F04') or all of that extension with '.pdf' instead of 'F04', but I cannot figure out a way to check for both at once. First I tried something like
links = webdriver.find_elements_by_partial_link_text('F04')
for l in links:
if l.find('.pdf') == -1:
continue
else:
#do some stuff
But unfortunately, the links are WebElements:
print(links[0])
>> <selenium.webdriver.remote.webelement.WebElement (session="78494f3527260607202e68f6d93668fe", element="0.8703868381417961-1")>
print(links[0].get_attribute('href'))
>> javascript:readfile2("F","2330","2015_2330_20160607F04.pdf")
so the conditional in the for loop above fails.
I see that I could probably access the necessary information in whatever that object is, but I would prefer to do the checks first when getting the links. Is there any way to check multiple conditions in the webdriver.find_elements_by_* methods?
You can try to use below code
links = [link.get_attribute('href') for link in webdriver.find_elements_by_partial_link_text('F04') if link.get_attribute('href').endswith('.pdf")')]
You can also try XPath as below
links = webdriver.find_elements_by_xpath('//a[contains(., "F04") and contains(#href, ".pdf")]')
Andersson's approach seems to work with a slight correction:
if link.get_attribute('href').endswith('.pdf')] rather than if link.get_attribute('href').endswith('.pdf")')], i.e. delete the ").

Python - CSV Module, Getting Information From a File

Here is the situation:
The first problem I'm having is with obtaining information from a CSV file. The purpose of the code I'm writing is to get a bunch of information on ZCTAs (zip codes), for a number of different cohorts (there are six currently being used, but the code is meant to be flexible to have any number of cohorts). One file contains the population, by cohort, for each ZCTA. Another file has the number of 'cases' (cases of cancer observed) for each cohort, for each ZCTA. Another file has the crude rate for each cohort, for the state of Iowa (the focus of this research), for the rate at which one can 'expect' to see the number of people who have cancer, for a population, by cohort. There are a couple of other files, but these are the focus, as this is where my issue is exhibited.
What my code does, initially, is to read the population file and get the population of each cohort by ZCTA. Each ZCTA, and the information, is stored in a list, which is then stored in a list of lists (nested), containing all of the ZCTAs. The code then gets the crude rate. Then, the crude rate is taken times the appropriate cohort, for each ZCTA and summed with all of the other cohorts within each ZCTA, to get the total number of people we can EXPECT to see having cancer, for each ZCTA. The population is also summed up. This information is stored in a another list, as well as a list containing all of the ZCTAs. This information will be the focus (The list of all of the ZCTAs, which each contain the total population and the total number of expected cases).
So, the problem is that I then need to take this newly acquired list and get the number of OBSERVED cases, for each cohort, sum those together, append it to the appropriate ZCTA and write it to a new file. I have code implemented that does this fine, EXCEPT that the bottom 22 or so ZCTAs don't get the number of observed cases. I don't know if it is the code, or what, but it works for all of the other 906, but doesn't get the bottom 22.
The reader will find sample data for the files I've discussed (the observed case file, and the output file) at: Gist
Here is the code I'm using:
`expectedcsv = open('ExpectedCases.csv', 'w', newline= '')
expectedwriter = csv.writer(expectedcsv, delimiter = ',')
expectedHeader = ['zcta', 'expected', 'pop', 'observed']
thecasesreader = csv.reader(thecasescsv, delimiter = ',')
for zcta in zctaPop:
caseCounter = 0
thecasescsv = open('NewCaseFile.csv', 'r', newline = '')
thecasesreader = csv.reader(thecasescsv, delimiter = ',')
for case in thecasesreader:
if case[0] == zcta[0]:
for i in range(3, len(case)):
caseCounter += int(case[i])
zcta.append(caseCounter)
expectedwriter.writerow(zcta)
expectedcsv.close()
thecasescsv.close()`
Something else I would also like to bring up is that later on in the code, the actual purpose for all of this, is to create an SMR filter, for each grid point. The grid points are somewhat arbitrary they have been placed (via coordinates) over the entire state of Iowa. The SMR is the number of observed divided by the number of expected cases. The threshold, that is, how many expected cases for a particular filter, is set by the user. So, if a user wants a filter created on 150 expected cases (for each grid point), the code goes through each ZCTA, summing up the expected cases until greater than 150 are found. The distance to this last ZCTA is the 'radius' of the filter.
To do this, I built a distance matrix (the distance from each grid point to every ZCTA) and then sorted it, nearest to furthest. Because of the size of the file (2300 X 930), I have to read this file line by line and get all of the information from other files. So, starting with the nearest ZCTA, I get the population, expected cases, and observed cases (the problem with this file was discussed above) and add these each to their respective counter (one for population, one for observed and one for expected). Then it goes to the next closest ZCTA and does the same, until the the threshold is exceeded.
The problem here is that I couldn't use the CSV Module to read these files, as I was already reading from another file and the index would be lost. So, I had to use just the regular filename.read(), which then required some interesting use of maketrans and .translate. I'm not sure its efficient or works great. Everything seems to be fine, but without the above problem being fixed, it's impossible to tell. I have included the code below, but was wondering if anybody had any better ideas/suggestions?
`expectedCSV = open('ExpectedCases.csv', 'r', newline = '')
table = str.maketrans('\r', ' ')
content = expectedCSV.read()
expectedCSV.close()
content = content.translate(table)
content = content.split(sep = '\n')
newContent = []
for item in content:
newContent.append((item.split(sep= ',')))
content = ' '
for item in newContent:
if item[0] == currentZcta:
expectedTotal += (float(item[1]))
totalPop += (float(item[2]))
totalObservedCount += (float(item[3]))`
Also, I couldn't figure out how to color the methods blue and the variables red, as some of the more awesome users of this site do. I would be very much interested in learning how to do that for future posts.
If anybody needs more info or anything clarified to help answer/formulate a solution, please, by all means, ask! Thanks for taking the time to read!
So, I ended up "solving" this by computing the observed along with the expected and population, by opening the file for each ZCTA computed. This did not really solve the issue I was dealing with, but rather found a way around it. I'm somewhat disappointed that more people didn't view and/or respond to this. If someone comes up with an answer to the actual problem, by all means, post it here. -Mike

Resources