def write_blog(self): # 写入文章标题 ele_title = WebDriverWait(self.driver, self.timeout).until( lambda x: x.find_element_by_xpath("//*[@placeholder='请输入文章标题']")) ele_title.clear() ele_title.send_keys(self.title) # 写入文章正文 ele_edit = WebDriverWait( self.driver, self.timeout).until(lambda x: x.find_element_by_xpath( "//textarea[@placeholder='开始编辑...']")) ele_edit.clear() ele_edit.click() # 由于某些编辑器对输入有自动格式化,可通过模拟复制粘贴的方式解决 # ele_edit.send_keys(self.content) pyperclip.copy(self.content) k = pykeyboard.PyKeyboard() ele_edit.send_keys(Keys.CONTROL, 'a') ele_edit.send_keys(Keys.RETURN) time.sleep(1) # ele_edit.send_keys(Keys.CONTROL, 'v') k.press_keys(['Command', 'v']) k.press_keys(['Return']) time.sleep(1) # 点击发布按钮 ele_publish = self.driver.find_element_by_class_name( "ant-pro-footer-toolbar").find_element_by_xpath( "//button[@class='ant-btn ant-btn-primary']") ele_publish.click()
def write_blog(self): self.driver.close() window_handles = self.driver.window_handles self.driver.switch_to.window(window_handles[-1]) # 1. 输入文章标题 title = WebDriverWait(self.driver, self.timeout).until(lambda x : x.find_element_by_xpath("//input[@class='article-bar__title article-bar__title--input text-input']")) ActionChains(self.driver).click(title).perform() title.clear() title.send_keys(Keys.CONTROL, 'a') title.send_keys(Keys.DELETE) title.send_keys(self.title) # PS:下面这行代码很重要,卡了好久才解决┭┮﹏┭┮,不信可以试试注释掉这句 # 2.输入正文 通过键盘事件解决 editor = self.driver.find_element_by_xpath("//div[@class='cledit-section']") ActionChains(self.driver).click(editor).perform() pyperclip.copy(self.content) k = pykeyboard.PyKeyboard() time.sleep(1) k.press_keys(['Command', 'a']) k.press_keys(['Return']) time.sleep(0.5) k.press_keys(['Command', 'v']) k.press_keys(['Return']) time.sleep(2) # 3. 发布文章按钮 self.driver.find_element_by_xpath("//div[@class='article-bar__user-box flex flex--row']/button[@class='btn btn-publish']").click()
def execute(self): k = pykeyboard.PyKeyboard() scanner = Scanner() scanner.find_game() r = range(1, 2) for num, genome in zip(r, self.__genomes): print('genome_' + str(num)) scanner.reset() k.press_keys([k.control_l_key, 'r']) k.release_key(k.control_l_key) sleep(1) k.press_key(k.space) while True: try: obs = scanner.find_next_obstacle() inputs = [ obs['distance'] / 1000, obs['length'], obs['speed'] / 10 ] print(inputs) outputs = genome.forward(np.array(inputs, dtype=float)) print(outputs) if outputs[0] > 0.5: k.press_key(k.space) print('continue') except: break print("Improved") genome.fitness = scanner.get_fitness()
def setup(hass, config): """ Listen for keyboard events. """ import pykeyboard keyboard = pykeyboard.PyKeyboard() keyboard.special_key_assignment() hass.services.register(DOMAIN, SERVICE_VOLUME_UP, lambda service: keyboard.tap_key(keyboard.volume_up_key)) hass.services.register(DOMAIN, SERVICE_VOLUME_DOWN, lambda service: keyboard.tap_key(keyboard.volume_down_key)) hass.services.register(DOMAIN, SERVICE_VOLUME_MUTE, lambda service: keyboard.tap_key(keyboard.volume_mute_key)) hass.services.register(DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, lambda service: keyboard.tap_key(keyboard.media_play_pause_key)) hass.services.register(DOMAIN, SERVICE_MEDIA_NEXT_TRACK, lambda service: keyboard.tap_key(keyboard.media_next_track_key)) hass.services.register(DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, lambda service: keyboard.tap_key(keyboard.media_prev_track_key)) return True
class Keyboard(): """The class Keyboard is a simple library of basing functions."""; k = pykeyboard.PyKeyboard() def shell(self, args): """The function is a special shell."""; k = Keyboard.k; text = str(args['key']); k.type_string(text);
def response(self, interval=config): material = self.get_material(interval) keyboard = pykeyboard.PyKeyboard() for m in material: self.write_clipboard(m) keyboard.tap_key(keyboard.enter_key) keyboard.press_key(keyboard.control_l_key) keyboard.tap_key('V') keyboard.release_key(keyboard.control_key) keyboard.tap_key(keyboard.enter_key)
def response(self, interval=config.INTERVAL): ''' Use clipboard to solve problem of chinese coding ''' material = self.get_material(interval) keyboard = pykeyboard.PyKeyboard() for m in material: self.write_clipboard(m) keyboard.tap_key(keyboard.enter_key) keyboard.press_key(keyboard.control_key) keyboard.tap_key('V') keyboard.release_key(keyboard.control_l_key) keyboard.tap_key(keyboard.enter_key) sleep(0.5)
def load_state(filename): init() cmd = """ osascript -e 'tell application "System Events" to keystroke "d" using command down' """ os.system(cmd) k = pykeyboard.PyKeyboard() for key in list(filename)[:5]: k.tap_key(key) cmd = """ osascript -e 'tell application "System Events" to key code 36' """ os.system(cmd)
def __init__(self, population_size, chromosome_length, mutation_rate, crossover_rate, elitism_count): self.population = self.init_population(population_size, chromosome_length) #trained1 = [-0.7804749316601893, 0.1513393337247957, -0.2768261313809339, 0.4701464868308525, 0.3439301467453155, 0.8967267012585185, -0.073053272613403, -0.8093484800832229, 0.11935976376011337, 0.3656041574367368, -0.25653148336315446, -0.46913389704113073] #self.population.addIndividual(trained1, 0) self.mutation_rate = mutation_rate self.crossover_rate = crossover_rate self.elitism_count = elitism_count self.mlp = Network() self.scanner = Scanner() self.k = pykeyboard.PyKeyboard() self.up_pressed = False self.down_pressed = False self.scanner.find_game() self.k.press_key(self.k.alt_key) self.k.tap_key(self.k.tab_key) self.k.release_key(self.k.alt_key)
def input_command(keys, sleep_time, lag_param): cmd = """ osascript -e 'tell application "Nestopia" activate end tell' """ os.system(cmd) time.sleep(lag_param) k = pykeyboard.PyKeyboard() for key in keys: k.press_key(key) time.sleep(sleep_time) for key in keys: k.release_key(key)
def execute(self): k = pykeyboard.PyKeyboard() scanner = Scanner() scanner.find_game() for genome in self.__genomes: scanner.reset() k.press_keys(['Command', 'r']) k.release_key('Command') sleep(1) k.press_key(k.space) while True: try: obs = scanner.find_next_obstacle() inputs = [obs['distance'] / 1000, obs['length'], obs['speed'] /10] outputs = genome.forward(np.array(inputs, dtype=float)) if outputs[0] > 0.55: k.press_key(k.space) except: break genome.fitness = scanner.get_fitness()
def save_state(filename): cmd = """ osascript -e 'tell application "Nestopia" activate end tell' """ os.system(cmd) cmd = """ osascript -e 'tell application "System Events" to keystroke "f" using command down' """ os.system(cmd) k = pykeyboard.PyKeyboard() for key in list(filename): k.tap_key(key) cmd = """ osascript -e 'tell application "System Events" to key code 36' """ os.system(cmd)
def setup(hass, config): """ Listen for keyboard events. """ try: import pykeyboard except ImportError: logging.getLogger(__name__).exception( "Error while importing dependency PyUserInput.") return False keyboard = pykeyboard.PyKeyboard() keyboard.special_key_assignment() hass.services.register( DOMAIN, SERVICE_VOLUME_UP, lambda service: keyboard.tap_key(keyboard.volume_up_key)) hass.services.register( DOMAIN, SERVICE_VOLUME_DOWN, lambda service: keyboard.tap_key(keyboard.volume_down_key)) hass.services.register( DOMAIN, SERVICE_VOLUME_MUTE, lambda service: keyboard.tap_key(keyboard.volume_mute_key)) hass.services.register( DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, lambda service: keyboard.tap_key(keyboard.media_play_pause_key)) hass.services.register( DOMAIN, SERVICE_MEDIA_NEXT_TRACK, lambda service: keyboard.tap_key(keyboard.media_next_track_key)) hass.services.register( DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, lambda service: keyboard.tap_key(keyboard.media_prev_track_key)) return True
def publish_(self): # 1. 添加标签 add_tag = WebDriverWait(self.driver, self.timeout).until(lambda d: d.find_element_by_xpath('//div[@class="mark_selection_title_el_tag"]')) add_tag.click() tag_input = WebDriverWait(self.driver, self.timeout).until( lambda d: d.find_element_by_xpath('//input[@class="el-input__inner"]')) tag_input.clear() tag_input.click() time.sleep(1) for i, tag in enumerate(self.tags): tag_input.send_keys(tag, Keys.RETURN) time.sleep(1) self.driver.find_element_by_xpath("//button[@class='modal__close-button button']").click() # 2.添加分类 category = WebDriverWait(self.driver, self.timeout).until(lambda d: d.find_element_by_xpath('//button[@class="tag__btn-tag"]')) ActionChains(self.driver).move_to_element(category).click().perform() # 3.模拟键盘输入即可 k = pykeyboard.PyKeyboard() ActionChains(self.driver).click(category).perform() k.press_keys(['Return']) for category in self.categories: pyperclip.copy(category) time.sleep(1) k.press_keys(['Command', 'v']) k.press_keys(['Return']) time.sleep(2) # 4. 文章类型 select = Select(self.driver.find_element_by_xpath("//div[@class='form-entry__field']/select[@class='textfield']")) print(self.csdn_category) select.select_by_visible_text(self.csdn_category) # 5.发布 button = self.driver.find_element_by_xpath("//div[@class='modal__button-bar']/button[@class='button btn-b-red']") button.click()
def __init__(self): self.k = pykeyboard.PyKeyboard() self.m = pymouse.PyMouse()
if '_' in phrase: phrase = phrase.replace("_", " ") try: times = int(args[3]) except ValueError: raise SystemExit, "ERROR: Cannot convert times to a number!" if len(args) > 4: activateKey = args[4] else: activateKey = "'" activated = False k = pykeyboard.PyKeyboard() run = True #Typing the phrase out def write(): global activated k.tap_key(k.enter_key) for i in range(times): for letter in phrase: k.tap_key(letter) sleep(0.0015) activated = False #Loop for checking if the user presses the activate key and the run key
def __init__(self): self.keyboard = pykeyboard.PyKeyboard()
def __init__(self): PyKeyboardEvent.__init__(self) self.input = "" self.diagnostic = True self.k = pykeyboard.PyKeyboard()
def saveWebPage(self, url, dir_path=None): ''' 保存网页 :param url: 网页url :param dir_path: 保存路径不支持中文及其他非英文语言 :return: 成功保存返回DONE 各种原因中途退出返回FAIL 保存失败返回TIMEOUT ''' try: self.driver.get(url) time.sleep(1) # 滑到底部 js = "window.scrollTo(0,document.body.scrollHeight)" self.driver.execute_script(js) time.sleep(0.2) except Exception as e: traceback.print_exc() return FAIL # 检查路径 if not re.fullmatch(r'^[A-Za-z0-9 _/.-]+$', dir_path): print('存储文件夹名称中只能包含英文字母 数字 "_" "." "-", 您的输入为:' + dir_path) return FAIL # 检查文件夹是否存在 if not os.path.exists(dir_path): print("文件夹不存在!->" + dir_path) os.makedirs(dir_path) print("创建文件夹:" + dir_path) # 检查是否有重名网页 if os.path.exists(os.path.join(dir_path, self.driver.title + '.html')): print('网页已存在!->' + os.path.join(dir_path, self.driver.title + '.html') + ' url:' + url) return FAIL try: # 实现ctrl s k = pykeyboard.PyKeyboard() k.press_key(k.control_key) k.press_key("s") k.release_key("s") k.release_key(k.control_key) time.sleep(1) # 键入路径 str = os.path.abspath(dir_path) + os.path.sep k.tap_key(k.home_key) k.type_string(str) # 只能是键盘上有的字母数字 time.sleep(1) k.tap_key(k.enter_key) print("saving web page: " + os.path.join(str, self.driver.title + ".html")) except: traceback.print_exc() return FAIL # 检查是否保存成功,若30s内未成功则退出 for i in range(30): time.sleep(1) if os.path.exists(os.path.join(str, self.driver.title + ".html")): print("保存成功!") return DONE else: print("30s内未保存成功!->" + str + self.driver.title + '.html url:' + url) return TIMEOUT
########## IMPORTS ########## import time import numpy as np import sys import pyautogui import mss import cv2 import pykeyboard import locate from conf import show_computer_vision, buttons, ammo_upgrade, health_upgrade, basic_upgrades, ammo_bar, state_colors ########## GLOBALS ########## pyautogui.PAUSE = 0.0 # make mouse clicks instant keypress = pykeyboard.PyKeyboard() # the keyboard tool sct = mss.mss() # the screen capture tool bubble_radius = 80 # area around last click to not click immediately again sleepy_time = .500 # sleep between frames ammo_buy = 0 # initial amount of additional ammo to buy short_sleep = 0.25 # a small amount of time to wait between screen transations and such upgrade_time = 0.075 # wait time to make sure upgrade clicks get registered try: mon = locate.locate_game() except: print("""Nope! Doesn't look like you have the window open. Open a browser, go to http://www.crazygames.com/game/storm-the-house
def __init_keyboard (self): self.keyboard = pykeyboard.PyKeyboard() k = self.keyboard self.key_map = { \ 'accept' :k.accept_key, \ 'alt' :k.alt_key, \ 'left-alt' :k.alt_l_key, \ 'right-alt' :k.alt_r_key, \ 'apps' :k.apps_key, \ 'backspace' :k.backspace_key, \ 'begin' :k.begin_key, \ 'break' :k.break_key, \ 'cancel' :k.cancel_key, \ 'capital' :k.capital_key, \ 'caps-lock' :k.caps_lock_key, \ 'clear' :k.clear_key, \ 'control' :k.control_key, \ 'left-control' :k.control_l_key, \ 'right-control' :k.control_r_key, \ 'convert' :k.convert_key, \ 'delete' :k.delete_key, \ 'down' :k.down_key, \ 'end' :k.end_key, \ 'enter' :k.enter_key, \ 'escape' :k.escape_key, \ 'execute' :k.execute_key, \ 'final' :k.final_key, \ 'find' :k.find_key, \ 'hangeul' :k.hangeul_key, \ 'hangul' :k.hangul_key, \ 'hanja' :k.hanja_key, \ 'help' :k.help_key, \ 'home' :k.home_key, \ 'left-hyper' :k.hyper_l_key, \ 'right-hyper' :k.hyper_r_key, \ 'insert' :k.insert_key, \ 'junjua' :k.junjua_key, \ 'kana' :k.kana_key, \ 'kanji' :k.kanji_key, \ 'left' :k.left_key, \ 'linefeed' :k.linefeed_key, \ 'menu' :k.menu_key, \ 'left-meta' :k.meta_l_key, \ 'right-meta' :k.meta_r_key, \ 'mode-switch' :k.mode_switch_key, \ 'mode-change' :k.modechange_key, \ 'next' :k.next_key, \ 'nonconvert' :k.nonconvert_key, \ 'num-lock' :k.num_lock_key, \ 'page-down' :k.page_down_key, \ 'page-up' :k.page_up_key, \ 'pause' :k.pause_key, \ 'print' :k.print_key, \ 'print-screen' :k.print_screen_key, \ 'prior' :k.prior_key, \ 'redo' :k.redo_key, \ 'return' :k.return_key, \ 'right' :k.right_key, \ 'script-switch' :k.script_switch_key, \ 'scroll-lock' :k.scroll_lock_key, \ 'select' :k.select_key, \ 'shift' :k.shift_key, \ 'left-shift' :k.shift_l_key, \ 'shift-lock' :k.shift_lock_key, \ 'right-shift' :k.shift_r_key, \ 'sleep' :k.sleep_key, \ 'snapshot' :k.snapshot_key, \ 'left-super' :k.super_l_key, \ 'right-super' :k.super_r_key, \ 'sys-req' :k.sys_req_key, \ 'tab' :k.tab_key, \ 'undo' :k.undo_key, \ 'up' :k.up_key, \ 'left-windows' :k.windows_l_key, \ 'right-windows' :k.windows_r_key } # Add the standard typeable keys. self.key_map['space'] = ' ' for c in "`1234567890[]',.pyfgcrl/=\\aoeuidhtns-;qjkxbmwvz": self.key_map[c] = c # Add the function keys. for i,key in enumerate(k.function_keys): if key != None and key != 0: self.key_map['f{0}'.format(i)] = key # Add the numpad keys. for name,key in k.numpad_keys.iteritems(): if isinstance(name,str): name = name.replace('_','-').lower() self.key_map['numpad-{0}'.format(name)] = key # Delete unsupported keys. Log.record('Identifying unsupported keys.\n') Log.indent() keys_to_delete = [] for name,key in self.key_map.iteritems(): if key == 0 or key == None: Log.record("key '{0}' is not available on this machine.\n".format(name)) keys_to_delete.append(name) Log.unindent() for name in keys_to_delete: del self.key_map[name] #Log.record('key_map = {\n') #Log.indent() #for name,key in self.key_map.iteritems(): #Log.record('{0}:{1},'.format(name,key)) #Log.unindent() #Log.record('}') Log.record('Available key names: [\n') Log.indent() available_key_names = sorted(self.key_map.keys()) for available_key_name in available_key_names: Log.record("'{0}',\n".format(available_key_name)) Log.unindent() Log.record(']\n') # This is really just for printing the key names based on key codes. self.key_map_inverse = {key:name for name,key in self.key_map.iteritems()} #Log.record('{0}'.format(self.key_map_inverse)) self.held_keys = set([])
def execute(self): time.sleep(2) k = pykeyboard.PyKeyboard() scanner = Scanner(self.driver) for i, genome in enumerate(self.__genomes): print('---------------Genome Number: {0}---------------'.format(i + 1)) time.sleep(0.1) k.tap_key(' ') _ = self.wait_for_dino_jump(time.time()) scanner.find_game() start_time = time.time() running_time = 0 scanner.reset() t = 0 jump = 0 jumpDist = 0 flag = True while flag: stop = 0 t += 1 obs = scanner.find_next_obstacle() if not stop: inputs = [ obs['distance'] / 100, obs['length'] / 100, obs['speed'] / 100 ] outputs = genome.forward(np.array(inputs, dtype=float)) if outputs[0] > 0.55: k.tap_key(' ') jump += 1 stop = 1 print('speed: {0}'.format(obs['speed'])) if stop: StopTimeStart = time.time() while True: if (time.time() - StopTimeStart) >= 0.65: obs = scanner.find_next_obstacle() if obs['speed'] == 0: flag = False #died running_time = time.time() - start_time - 0.65 jumpDist = obs['distance'] break else: flag = True stop = 0 break elif obs['speed'] == 0: StopTimeStart = time.time() while True: if (time.time() - StopTimeStart) >= 0.65: obs = scanner.find_next_obstacle() if obs['speed'] == 0: flag = False #died running_time = time.time() - start_time - 0.65 jumpDist = 1000 #died because no jump, give high penalty break else: flag = True stop = 0 break print('t: {0}'.format(t)) genome.fitness = 1.5 * scanner.get_fitness( ) + 15 * running_time - (jumpDist / 100) print('Gemome fitness: {0}'.format(genome.fitness))
#GLOBALS COLORMAP = {(204, 192, 179):None, (238, 228, 218):2, (237, 224, 200):4, (223, 212, 201):4,(242, 177, 121):8,(245, 149, 99):16,(246, 124, 95):32,(246, 94, 59):64,(237, 207, 114):128,(237, 204, 97):256,(237, 200, 80):512,(237, 197, 63):1024,(237, 194, 46):2048} NEWCOLOR = (143, 122, 102) GRIDCOLOR = (187, 173, 160) COLORS = COLORMAP.keys()+[GRIDCOLOR] DEPTHS = {} DEPTHS["unreasonable"] = [2]*17 DEPTHS["fast"] = [2]*8+[3]*5+[4]*4 DEPTHS["effective"] = [2]*6+[3]*4+[4]*7 DEPTHS["thorough"] = [3]*4+[4]*9+[5]*4 #Dimensions of cell: #106,15;121 MOUSE = pymouse.PyMouse() KEYBOARD = pykeyboard.PyKeyboard() KEYS = {(-1,0):KEYBOARD.left_key,(1,0):KEYBOARD.right_key,(0,-1):KEYBOARD.up_key,(0,1):KEYBOARD.down_key} KEYNAMES = {(-1,0):"left",(1,0):"right",(0,1):"down",(0,-1):"up"} class AutomaticBoard(AbstractBoard): def __init__(self,*args,**kwargs): AbstractBoard.__init__(self,*args) if "profile" in kwargs: self.profile = kwargs["profile"] else: self.profile = "flexible" if self.profile=="flexible": self.Depth = DEPTHS["unreasonable"] else: self.Depth = DEPTHS[self.profile]