So I'm almost done completing a genetic algorithm for the snake game in python for this javascript snake game: http://patorjk.com/games/snake/
I've been getting an error for my code:
import selenium, os, urllib
from selenium import webdriver
import win32com.client as comctl
from random import randint
from operator import add
import time
import random
import lxml
from lxml import html
import requests
page=requests.get("http://patorjk.com/games/snake/")
tree=lxml.html.fromstring(page.content)
chromedriver="C:/Python34/Scripts/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
wsh = comctl.Dispatch("WScript.Shell")
wsh.AppActivate("patorjk.com/games/snake/")
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
driver.get('http://patorjk.com/games/snake/')
hidden_element = driver.find_element_by_id('sbTryAgain0')
def createIndividual(length, mintim, maxtim):
return [[random.uniform(mintim,maxtim) for x in range(length)],[randint(0,3) for x in range(length)],[]]
def changeInt(int1):
if(int1==0):
return '{UP}'
if(int1==1):
return '{RIGHT}'
if(int1==2):
return '{DOWN}'
if(int1==3):
return '{LEFT}'
def run(ind):
for x in range(len(ind[0])):
if hidden_element.is_displayed():
break
wsh.SendKeys(" ")
time.sleep(ind[0][x])
wsh.SendKeys(changeInt(ind[1][x]))
print(changeInt(ind[1][x]))
def indfit(time, pts):
tree=lxml.html.fromstring(page.content)
points=tree.xpath('//div[#class="snake-panel-component"]/text()')
for i in points:
if(points[i-1]==" " and points[i-2]==":"):
pts=int(points[i:len(points)-1])
#return (pts/time)
return pts
def createPopulation(size, length, mintim, maxtim):
population=[]
for x in range(size):
population.append(createIndividual(length, mintim, maxtim))
return population
def cyclePop(pop):
index1=0
for x in pop:
start_time=time.time()
pop1=pop[index1]
run(pop1)
pop[index1][2]=indfit(time.time()-start_time,1)
print("Fitness of individual ",(index1+1),": ",pop[index1][2])
wsh.SendKeys(" ")
index1+=1
print("Population Fitness: ",popFitScore(pop))
def popFitScore(pop):
sum1=0
for x in pop:
sum1+=x[2]
return sum1/len(pop)
def bubble_sort(items):
""" Implementation of bubble sort """
for i in range(len(items)):
for j in range(len(items)-1-i):
if items[j][2] > items[j+1][2]:
items[j], items[j+1] = items[j+1], items[j] # Swap!
def mixtraitscross(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=ind2[index1]
index1+=1
def mixtraitsavg(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=(ind1[index1]+ind2[index1])/2
index1+=1
def evolve(pop,mutrate,killpercent,sammin,sammax):
bubble_sort(pop)
startmutlen=(len(pop)-(killpercent*len(pop)))
mutrateind=mutrate*len(pop[0][0])
for ig in pop:
index1=pop.index(ig)
if index1>startmutlen:
for g in range(int(mutrateind)):
ig[0][randint(0,len(pop[0][0])-1)]=randint(0,3)
ig[1][randint(0,len(pop[0][0])-1)]=random.uniform(sammin,sammax)
else:
for iff in range(int(startmutlen-1)):
mixtraitscross(pop[index1][0],pop[index1+1][0])
mixtraitsavg(pop[index1][1],pop[index1+1][1])
#createPopulation(10, 20, 0, 5)
index8=0
while(index8<=50):
x=createPopulation(5,10,0,2)
cyclePop(x)
evolve(x,.30,.5,0,2)
index8+=1
so this is my code and i'm trying to make it so that if the element that says "You Died :(", it will stop running the individual and it will apply the time to the individual's fitness. I'm getting really confused with all of this chromedriver stuff with selenium and if I were able to get it to work, It would be perfect. the comment that says
#return (pts/time)
is what I want to be there, but until I am able to get the selenium working, the time is the same. I made it so that the time would be the same, but I want it so that it cuts off after it dies. Right now, I'm just having errors working with chromedriver, and I'm not exactly sure it's what I even want to be using. This is my error:
Traceback (most recent call last):
File "H:\Senior Year\CSAP2\Snakegenalg\SnakeJSGenAlg.py", line 27, in <module>
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
self.service.start()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site- packages\selenium\webdriver\common\service.py", line 86, in start
self.assert_process_still_running()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0
Sorry if I'm really bad at coding and I'm getting bad at this simple stuff, I'm just in high school and learned python this month. I'm not using the shorthand for stuff right now because it confuses me, but I know my code is easy to follow
Related
I'm writing a script to fill a monthly tax form using pyautogui.
There are 2 images to be clicked on.
Issue
I'm getting the following error on the second one:
PS C:\Users\Rodrigo\OneDrive\Documentos\Python> & C:/Users/Rodrigo/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Rodrigo/OneDrive/Documentos/Python/SIFERE/saf.py
Traceback (most recent call last):
File "c:\Users\Rodrigo\OneDrive\Documentos\Python\SIFERE\saf.py", line 16, in <module>
pyautogui.click('SIFERE/agrega_saf.png')
File "C:\Users\Rodrigo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui\__init__.py", line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "C:\Users\Rodrigo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui\__init__.py", line 980, in click
x, y = _normalizeXYArgs(x, y)
TypeError: cannot unpack non-iterable NoneType object
PS C:\Users\Rodrigo\OneDrive\Documentos\Python>
Code
import pyautogui, time
time.sleep(3)
anio='2015'
mes='abril'
secuencia='1'
monto='1234.56'
pyautogui.click('SIFERE/periodo.png')
pyautogui.press('tab')
pyautogui.write(anio)
pyautogui.press('tab')
pyautogui.write(mes)
pyautogui.press('tab')
pyautogui.write(secuencia)
pyautogui.press('tab')
pyautogui.write(monto)
pyautogui.click('SIFERE/agrega_saf.png')
I've copied that exact same line to another py file and it works, but not on this one.
I think you want to locate the given images on your screen.
Therefor PyAutoGUI has the function locateOnScreen(image) which returns a location. If the image was found, the location is defined otherwise it's None.
See also: How to detect an image and click it with pyautogui?
Try to locate the given images first. If they were found, then continue with your input.
Code
import pyautogui, time
anio='2015'
mes='abril'
secuencia='1'
monto='1234.56'
def find_image_or_exit(image):
i = 1
while location == None and i < 3: # try max 3 times (for 9 seconds)
time.sleep(3) # wait 3 seconds
location = pyautogui.locateOnScreen(image)
i += 1
if location == None:
print(f"Sorry! Image {image} not found on screen. Aborting!")
exit()
return location
def enter_period():
location = find_image_or_exit('SIFERE/periodo.png')
pyautogui.click(location)
pyautogui.press('tab')
pyautogui.write(anio)
pyautogui.press('tab')
pyautogui.write(mes)
pyautogui.press('tab')
pyautogui.write(secuencia)
pyautogui.press('tab')
pyautogui.write(monto)
def add_saf():
location = find_image_or_exit('SIFERE/agrega_saf.png')
pyautogui.click(location)
# main steps
enter_period()
add_saf()
I have multiple py files with unit tests specified for specific module.
I want to import these unittests to seperate py file and run them from there, but I have trouble getting it working.
example of one of the unittest:
from webdriver_manager.chrome import ChromeDriverManager
from to_import import acceptConsent, URL_poznavacky, URL_poznavacky_vikendy, URL_poznavacky_rodiny, URL_pobocky
import time
from selenium import webdriver
import unittest
class TestPobocky_D(unittest.TestCase):
def setup_method(self, method):
self.driver = webdriver.Chrome(ChromeDriverManager().install())
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_pobocky_D(self):
self.driver.get(URL_pobocky)
acceptConsent(self.driver)
self.driver.maximize_window()
time.sleep(2)
mapa = self.driver.find_element_by_xpath("//*[#class='leaflet-pane leaflet-tile-pane']") ## jen jeden element, no need to call find_elementS
mapaDisplayed = mapa.is_displayed()
assert mapaDisplayed == True
mapaKolecka = self.driver.find_elements_by_xpath("//*[#class='leaflet-marker-icon marker-cluster marker-cluster-medium leaflet-zoom-animated leaflet-interactive']")
y=0
for _ in mapaKolecka:
mapaKoleckaDisplayed = mapaKolecka[y].is_displayed()
y=y+1
print("mapa kolecka")
assert mapaKoleckaDisplayed == True
pobockaBoxiky = self.driver.find_elements_by_xpath("//*[#class='f_branch-header f_anchor']")
x=0
for _ in pobockaBoxiky:
pobockaBoxikyDisplay = pobockaBoxiky[x].is_displayed()
print("boxiky")
assert pobockaBoxikyDisplay == True
x=x+1
basicInfo = self.driver.find_elements_by_xpath("//*[#class='f_branch-basicInfo']")
a=0
for _ in basicInfo:
basicInfoDisplay = basicInfo[a].is_displayed()
print("basic info ")
assert basicInfoDisplay == True
a=a+1
I want to import the whole class TestPobocky_D to new file and run it in seperate py file. I tried following:
import unittest
from pobocky import TestPobocky_D
TestPobocky_D(unittest.TestCase)
that just gives me this error
"Traceback (most recent call last):
File "C:/Users/KDK/Desktop/Automation_Local_Deploy_PyCharm/starter_local.py", line 4, in <module>
TestPobocky_D(unittest.TestCase)
File "C:\Users\KDK\anaconda3\lib\unittest\case.py", line 433, in __init__
testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string"
Anyone who can help me with this please ? Or point me to the right direction how to go about this.
Thanks in advance for every response
Can you please try as below?
starttest.py
import unittest
from pobocky import TestPobocky_D
if __name__ == '__main__':
unittest.main(argv=[''],verbosity=2, exit=False)
Run the command "python -m unittest starttest.py"
import pyautogui as pt
from time import sleep
import pyperclip
import random
sleep(3)
position1 = pt.locateOnScreen("whatsapp/smile.png", confidence=.6)
x = position1[0]
y = position1[1]
# Gets Message
def get_message():
global x, y
position = pt.locateOnScreen("whatsapp/smile.png", confidence=.6)
x = position[0]
y = position[1]
pt.moveTo(x, y, duration=.05)
get_message()
When I try to run this code and open Whatsapp desktop, it fails and shows an error message like
OSError: Failed to read whatsapp/smile.png because file is missing, has improper permissions, or is an unsupported or invalid format
The title and the image format are correct. I've checked it many times. Any other suggestions on what might be the issue here?
I need to get all the elements on a page and iterate through them to search each element.
currently I am using, driver.find_elements_by_xpath('//*[#*]')
However, there can be a delay in completing the line of code above on larger pages. Is there a way to retrieve the results in increments of 100 elements? Or at least add a timeout?
Terminating driver.find_elements_by_xpath('//*[#*]') inside a multithread is the only why I currently think I can solve this.
I need to find all elements on a page that contain certain strings. For example. elem.get_attribute('outerHTML').find('type="submit"') != -1 … and so on and so forth … I also need their proximity to each other to compare index positions
Thanks!
import Globalz ###### globals import is an empty .py file
import threading
import time
import ctypes
def find_xpath():
for i in range(5):
print(i)
time.sleep(1)
Globalz.curr_value = 'DONE!'
### this is where the xpath retrieval goes (ABOVE loop is for example purposes only)
def stopwatch(info):
curr_time = 0
failed = False
Globalz.curr_value = ''
thread1 = threading.Thread(target=info['function'])
thread1.start()
while thread1.is_alive() is True:
if curr_time >= info['timeout']: failed = True; ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread1.ident), ctypes.py_object(SystemExit))
curr_time += 1; time.sleep(1)
if failed is True: return info['failed_returns']
if failed is False: return Globalz.curr_value
betty = stopwatch({'function': find_xpath, 'timeout': 10, 'failed_returns': 'failed'})
print(betty)
If anyone is interested here is a solution. I've created a wrapper called stopwatch()
I put the functions from the following program into a module but when I import the module into a separate program and call the functions I get an error (see below). What do I need to do for the functions to run correctly using the module? Any help is much appreciated.
Original Program:
def print_m(unprinted, completed):
while unprinted:
current = unprinted.pop()
print("Printing: " + current)
completed.append(current)
def show_completed(completed):
print("\nThe following have been printed:")
for completed_item in completed:
print(completed_item)
unprinted = ['star', 'sword', 'model']
completed = []
print_m(unprinted, completed)
show_completed(completed)
Putting the functions in a module - printing_functions.py:
def print_m(unprinted, completed):
while unprinted:
current = unprinted.pop()
print("Printing: " + current)
completed.append(current)
def show_completed(completed):
print("\nThe following have been printed:")
for completed_item in completed:
print(completed_item)
Wrote separate program to import the module:
import printing_functions as pf
unprinted = ['star', 'sword', 'model']
completed = []
pf.print_m(unprinted, completed)
pf.show_completed(completed)
When I run the program I get the following error:
NameError: name 'completed' is not defined
UPDATE:
I used shorter terms in the code above and it DOES appear to work, which makes me more baffled. Posting the original code below. If the above works, why doesn't the module below work?
def print_models(unprinted_designs, completed_designs):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
#Simulate creating a 3D print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
Module
def print_models(unprinted_designs, completed_designs):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
#Simulate creating a 3D print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
New Program
import printing_functions as pf
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
Traceback:
Traceback (most recent call last):
File "/home/pi/Documents/Python Projects/python_work/8-15_printing_models.py", line 6, in
pf.print_models(unprinted_designs, completed_models)
File "/home/pi/Documents/Python Projects/python_work/printing_functions.py", line 11, in print_models
completed_models.append(current_design)
NameError: name 'completed_models' is not defined