Search code examples
pythonpython-3.xpyautogui

PyAutoGUI - opens Chrome console in wrong browser


So I've created a Python script which uses selenium to automate some stuff on a web page and I am having a small problem with PyAutoGUI module.

I am using it to Copy & Paste some data into the previously opened Chrome console and that works just fine. So basically when I run the script, a new instance of Chrome browser will be opened and then I will paste some .js script in the console of that instance and send 'ENTER' key with PyAutoGUI module.

The problem is that if I click on some other Chrome session, the code which opens the console pyautogui.hotkey('ctrl', 'shift', 'i') will execute in the session I am currently browsing in and not in the newly started one with selenium.

Any suggestions how to set a filter based on Chrome session?

Here's the code:

driver = Chrome()
driver.get('randomUrl')

def loopProfiles():
  btnKey = driver.find_element_by_xpath('//*[@id="L1"]/div[1]/div[2]/div[4]/div[5]/div/a')
  btnKey.click()

  formEmail = driver.find_element_by_xpath('//*[@id="L1"]/div[2]/div[2]/div/div[2]/form/div/div[1]/input')
  formPass = driver.find_element_by_xpath('//*[@id="L1"]/div[2]/div[2]/div/div[2]/form/div/div[2]/input')
  # Authenticate
  formEmail.send_keys('user')
  formPass.send_keys('pass')

  time.sleep(1)
  btnLogin = driver.find_element_by_xpath('//*[@id="L1"]/div[2]/div[2]/div/div[2]/form/div/div[4]/button[2]')
  btnLogin.click()

  time.sleep(2)
  liveFeed = driver.find_element_by_xpath('//*[@id="L1"]/div[5]/div/div[1]/div/div[1]/div/select/option[3]')
  liveFeed.click()

  time.sleep(5)
  pyautogui.hotkey('ctrl', 'shift', 'j')

  time.sleep(1)
  # copy content from cent-clicks.js file
  jsScript = open('script.js', 'r')
  jsScriptContent = jsScript.read()

  time.sleep(1)
  pyperclip.copy(jsScriptContent)

  jsScript.close()

  time.sleep(1)
  pyautogui.hotkey('ctrl', 'v')
  time.sleep(1)
  pyautogui.hotkey('enter')

I am very very new to Python :)


Solution

  • Never-mind, I've changed the code a bit and found a way to execute js file directly so everything works fine.

    def startClicking():
      jsScript = open('clicks.js', 'r')
      jsScriptContent = jsScript.read()
      time.sleep(2)
      driver.execute_script(jsScriptContent)
      time.sleep(1)
      jsScript.close()