Hello i am trying to make a app that sends a key press 2 chrome the current code i have is:
#you will need the win32 libraries for this snippet of code to work, Links below
import win32gui
import win32con
import win32api
from time import sleep
#[hwnd] No matter what people tell you, this is the handle meaning unique ID,
#["Notepad"] This is the application main/parent name, an easy way to check for examples is in Task Manager
#["test - Notepad"] This is the application sub/child name, an easy way to check for examples is in Task Manager clicking dropdown arrow
#hwndMain = win32gui.FindWindow("Notepad", "test - Notepad") this returns the main/parent Unique ID
hwndMain = win32gui.FindWindow("Notepad", "test - Notepad")
#["hwndMain"] this is the main/parent Unique ID used to get the sub/child Unique ID
#[win32con.GW_CHILD] I havent tested it full, but this DOES get a sub/child Unique ID, if there are multiple you'd have too loop through it, or look for other documention, or i may edit this at some point ;)
#hwndChild = win32gui.GetWindow(hwndMain, win32con.GW_CHILD) this returns the sub/child Unique ID
hwndChild = win32gui.GetWindow(hwndMain, win32con.GW_CHILD)
#print(hwndMain) #you can use this to see main/parent Unique ID
#print(hwndChild) #you can use this to see sub/child Unique ID
#While(True) Will always run and continue to run indefinitely
while(True):
#[hwndChild] this is the Unique ID of the sub/child application/proccess
#[win32con.WM_CHAR] This sets what PostMessage Expects for input theres KeyDown and KeyUp as well
#[0x44] hex code for D
#[0]No clue, good luck!
#temp = win32api.PostMessage(hwndChild, win32con.WM_CHAR, 0x44, 0) returns key sent
temp = win32api.PostMessage(hwndChild, win32con.WM_CHAR, 0x44, 0)
#print(temp) prints the returned value of temp, into the console
print(temp)
#sleep(1) this waits 1 second before looping through again
sleep(1)
but my issue is how i find chrome seing as it changes it name to the active tab and using this does not work either:
hwndMain = win32gui.FindWindow("Google Chrome", None)
in similar thread i saw this worked for people. and your code as is by changing title name works for me but you need to modify the title input order to this format.
hwndMain = win32gui.FindWindow( "Google Chrome" , None)
TO
hwndMain = win32gui.FindWindow( None , "Google Chrome")
Related
I've tried pyimessage, applescript, and osascript. The only thing I could find that seemed promising was this older stackoverflow question:
Send group iMessage using applescript
I wasn't able to get that working. Has anyone been able to send to an existing group chat?
I can send individual messages on applescript. I can also send to the same message to multiple people. What I can't do is send to a group chat. I've got a group name containing two people named in my icloud and in my contacts and in a current chat. Here's the code I do that with:
import PySimpleGUI as sg
import sys
import subprocess
from os import system, name
from playsound import playsound
people = "Firstname Lastname", "Firstname Lastname"
msg = 'test'
def onCall():
applescript = (
"""
set people to "{0}"
tell application "Messages"
repeat with myBuddy in buddies
--get properties of myBuddy
if name of myBuddy is in people then
send "{1}" to myBuddy
end if
end repeat
end tell
""".format(people, msg
)
)
args = [
item
for x in [("-e", l.strip()) for l in applescript.split("\n") if l.strip() != ""]
for item in x
]
proc = subprocess.Popen(["osascript"] + args, stdout=subprocess.PIPE)
progname = proc.stdout.read().strip()
I call the function with a clickable button that does send messages when the Firstname and Lastname are known contacts.
I don't get an error message. The text just doesn't send when I try to change any of the values to 'TestGroup' (which is what I have my group chat named'.
After trying to break down code from GitHub and find any youtube videos that talk about this I'm starting to give up, so I'm hoping one of you can please help me. All I want to be able to do is monitor a games memory addresses value. For example, let's say in the game Minecraft the health value and the memory address is:
Address: 001F6498
Value: 20
How do I turn this value into a variable in Python?
Code Thought Process:
import pywin32
pid = 5601
address = 001F6498
ReadProcessMemory(pid, address):
print(Value)
#In this example i would like it to print 20
You need to get a handle to the process first. Here is some code that does so using OpenProcess() FindWindow() and GetWindowThreadProcessId() to get the handle to the process. Also included is a little function to properly read the correct size variable and store it correctly. This method can be used to read pointers, utilizing "i" to denote an integer type.
import win32api
import win32gui
import win32process
from ctypes import *
from pymem import *
PROCESS_ALL_ACCESS = 0x1F0FFF
ReadProcessMemory = windll.kernel32.ReadProcessMemory
def read_memory(procId, address, type):
buffer = (ctypes.c_byte * getlenght(type))()
bytesRead = ctypes.c_ulonglong(0)
readlenght = getlenght(type)
ReadProcessMemory(procId, address, buffer, readlenght, byref(bytesRead))
return struct.unpack(type, buffer)[0]
hWnd = win32gui.FindWindow(0, ("WINDOW NAME HERE"))
pid=win32process.GetWindowThreadProcessId(hWnd)
handle = pymem.Pymem()
handle.open_process_from_id(pid[1])
procBaseAddress = handle.process_base
hProc = windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, 0, pid[1])
value = ReadProcessMemory(hProc, ADDRESS_OF_VARIABLE_TO_READ, "i")
print(value)
Credits to a friend, puppetmaster, who taught me how to do this
Fairly new to python, I learn by doing, so I thought I'd give this project a shot. Trying to create a script which finds the google analytics request for a certain website parses the request payload and does something with it.
Here are the requirements:
Ask user for 2 urls ( for comparing the payloads from 2 diff. HAR payloads)
Use selenium to open the two urls, use browsermobproxy/phantomJS to
get all HAR
Store the HAR as a list
From the list of all HAR files, find the google analytics request, including the payload
If Google Analytics tag found, then do things....like parse the payload, etc. compare the payload, etc.
Issue: Sometimes for a website that I know has google analytics, i.e. nytimes.com - the HAR that I get is incomplete, i.e. my prog. will say "GA Not found" but that's only because the complete HAR was not captured so when the regex ran to find the matching HAR it wasn't there. This issue in intermittent and does not happen all the time. Any ideas?
I'm thinking that due to some dependency or latency, the script moved on and that the complete HAR didn't get captured. I tried the "wait for traffic to stop" but maybe I didn't do something right.
Also, as a bonus, I would appreciate any help you can provide on how to make this script run fast, its fairly slow. As I mentioned, I'm new to python so go easy :)
This is what I've got thus far.
import browsermobproxy as mob
from selenium import webdriver
import re
import sys
import urlparse
import time
from datetime import datetime
def cleanup():
s.stop()
driver.quit()
proxy_path = '/Users/bob/Downloads/browsermob-proxy-2.1.4-bin/browsermob-proxy-2.1.4/bin/browsermob-proxy'
s = mob.Server(proxy_path)
s.start()
proxy = s.create_proxy()
proxy_address = "--proxy=127.0.0.1:%s" % proxy.port
service_args = [proxy_address, '--ignore-ssl-errors=yes', '--ssl-protocol=any'] # so that i can do https connections
driver = webdriver.PhantomJS(executable_path='/Users/bob/Downloads/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs', service_args=service_args)
driver.set_window_size(1400, 1050)
urlLists = []
collectTags = []
gaCollect = 0
varList = []
for x in range(0,2): # I want to ask the user for 2 inputs
url = raw_input("Enter a website to find GA on: ")
time.sleep(2.0)
urlLists.append(url)
if not url:
print "You need to type something in...here"
sys.exit()
#gets the two user url and stores in list
for urlList in urlLists:
print urlList, 'start 2nd loop' #printing for debug purpose, no need for this
if not urlList:
print 'Your Url list is empty'
sys.exit()
proxy.new_har()
driver.get(urlList)
#proxy.wait_for_traffic_to_stop(15, 30) #<-- tried this but did not do anything
for ent in proxy.har['log']['entries']:
gaCollect = (ent['request']['url'])
print gaCollect
if re.search(r'google-analytics.com/r\b', gaCollect):
print 'Found GA'
collectTags.append(gaCollect)
time.sleep(2.0)
break
else:
print 'No GA Found - Ending Prog.'
cleanup()
sys.exit()
cleanup()
This might be a stale question, but I found an answer that worked for me.
You need to change two things:
1 - Remove sys.exit() -- this causes your programme to stop after the first iteration through the ent list, so if what you want is not the first thing, it won't be found
2 - call new_har with the captureContent option enabled to get the payload of requests:
proxy.new_har(options={'captureHeaders':True, 'captureContent': True})
See if that helps.
Im new to python and figured that best way to learn is by practice, this is my first project.
So there is this fantasy football website. My goal is to create script which logins to site, automatically creates preselected team and submits it.
I have managed to get to submitting team part.
When I add a team member this data gets sent to server:
https://i.gyazo.com/e7e6f82ca91e19a08d1522b93a55719b.png
When I press save this list this data gets sent:
https://i.gyazo.com/546d49d1f132eabc5e6f659acf7c929e.png
Code:
import requests
with requests.Session() as c:
gameurl = 'here is link where data is sent'
BPL = ['5388', '5596', '5481', '5587',
'5585', '5514', '5099', '5249', '5566', '5501', '5357']
GID = '168'
UDID = '0'
ACT = 'draft'
ACT2 = 'save_draft'
SIGN = '18852c5f48a94bf3ee58057ff5c016af'
# eleven of those with different BPL since 11 players needed:
c.get(gameurl)
game_data = dict(player_id = BPL[0], action = ACT, id = GID)
c.post(gameurl, data = game_data)
# now I need to submit my list of selected players:
game_data_save = dict( action = ACT2, id = GID, user_draft_id = UDID, sign = SIGN)
c.post(gameurl, data = game_data_save)
This code works pretty fine, but the problem is, that 'SIGN' is unique for each individual game and I have no idea how to get this data without using Chromes inspect option.
How can I get this data simply running python code?
Because you said you can find it using devtools I'm assuming SIGN is written somewhere in the DOM.
In that case you can use requests.get().text to get the HTML of the page and parse it with a tool like lxml or HTMLParser
Solved by posting all data without 'SIGN' and in return I got 'SIGN' in html.
I am using Selenium with Python and Chrome. I am trying to hold down various keys -- specifically "w, a, s, and d." I have found Selenium's action_chains.key_press action as well as the elem.send_keys method. The problem with the first method is that it only holds the key down for as long as it takes to complete an action chain. The problem with the elem.send_keys method is that it does not have an element to send the keys to.
I am trying to control a web-browser based robot with W-A-S-D, so I need to hold keys down for varying durations.
I have tried the following:
action_chains = ActionChains(driver)
action_chains.key_down("w")
action_chains.key_up("w")
as well as:
action_chains.key_press(elem, "w")
for x in range (0, 100):
action_chains.perform()
time.sleep(.01)
Neither are ideal.
The current driver for Chrome (version 2.30) implements the previous protocol where holding a key is only supported for a modifier key (Control, Shift, Alt, Command).
So this code works with Firefox but fails with Chrome since the keyUp event is emitted for each keyDown:
action_key_down_w = ActionChains(driver).key_down("w")
action_key_up_w = ActionChains(driver).key_up("w")
endtime = time.time() + 1.0
while True:
action_key_down_w.perform()
if time.time() > endtime:
action_key_up_w.perform()
break
But, since version 2.30, the Chrome driver supports the send_command to directly send a raw command via the devtools protocol.
So as a workaround, you can call Input.dispatchKeyEvent to emit low level events.
This is a working example with Selenium/Chrome to hold the key w during a second:
from selenium import webdriver
import json, time
def dispatchKeyEvent(driver, name, options = {}):
options["type"] = name
body = json.dumps({'cmd': 'Input.dispatchKeyEvent', 'params': options})
resource = "/session/%s/chromium/send_command" % driver.session_id
url = driver.command_executor._url + resource
driver.command_executor._request('POST', url, body)
def holdKeyW(driver, duration):
endtime = time.time() + duration
options = { \
"code": "KeyW",
"key": "w",
"text": "w",
"unmodifiedText": "w",
"nativeVirtualKeyCode": ord("W"),
"windowsVirtualKeyCode": ord("W")
}
while True:
dispatchKeyEvent(driver, "rawKeyDown", options)
dispatchKeyEvent(driver, "char", options)
if time.time() > endtime:
dispatchKeyEvent(driver, "keyUp", options)
break
options["autoRepeat"] = True
time.sleep(0.01)
driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/questions")
# set the focus on the targeted element
driver.find_element_by_css_selector("input[name=q]").click()
# press the key W during a second
holdKeyW(driver, 1.0)
Selenium actions chain Should only be used with modifier keys (Control, Alt and Shift). So you want to press only the character w-a-s-d. so that, it didn't work.
You can use any gui automation tools like pyautogui, etc.
please try below code and let me know.
import pyautogui
pyautogui.PAUSE = 10
pyautogui.keyDown('w')
pyautogui.keyUp('w')
pyautogui.PAUSE=10 command make 10 seconds pause after each PyAutoGUI call
According to the Selenium Documentation for key_down, it states:
Should only be used with modifier keys (Control, Alt and Shift).
I've searched through the docs for an alternative solution, but it appears the behavior to "hold down" non-modifier keys is not possible in Selenium.
ActionChains(driver).key_down("w").pause(0.1).key_up("w").perform()
By chaining key_down and key_up with a .pause(0.1) in between you can hold down keys for any custom duration.
Even though key_down should only be used with modifier keys according to the docs, it turns out that it can be used with any key.