Skip to main content

Python - PyQT5 integrated Selenium

import sys
import os
import time
import msvcrt

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QComboBox, QLineEdit
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import *
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import selenium.webdriver.support.ui as ui
from selenium.webdriver.support.ui import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC

class App(QWidget):
m_blnLooping = True
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
dir_path = os.path.dirname(os.path.realpath(__file__))
#Update Selenium chrome driver folder path here
chromedriver = dir_path + "/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chrome_options=options, executable_path= chromedriver)
driver.get("https://kite3.zerodha.com")
driver.maximize_window()

def __init__(self):
super().__init__()
self.title = 'Kite Automation - https://kite.zerodha.com/'
self.left = 40
self.top = 40
self.width = 500
self.height = 250

self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.yellow)
self.setPalette(p)

#Segment

self.lab_segment = QLabel('Segment :', self)
self.lab_segment.setAlignment(Qt.AlignRight)
self.lab_segment.move(60,60)
self.lab_segment.resize(50,20)

self.comsegment = QComboBox(self)
self.comsegment.move(140,58)
self.comsegment.resize(200,20)

self.btnrefresh = QPushButton("Refresh", self)
self.btnrefresh.move(355,57)
self.btnrefresh.clicked.connect(self.on_refresh)




#Option

self.lab_option = QLabel('Option :', self)
self.lab_option.setAlignment(Qt.AlignRight)
self.lab_option.move(60,90)
self.lab_option.resize(50,20)

self.comoption = QComboBox(self)
self.comoption.addItem("Buy")
self.comoption.addItem("Sell")
self.comoption.move(140,88)
self.comoption.resize(100,20)


#Current Price

self.lab_currentprice = QLabel('Price :', self)
self.lab_currentprice.setAlignment(Qt.AlignRight)
self.lab_currentprice.move(60,120)
self.lab_currentprice.resize(50,20)

self.labvalue = QLabel('...', self)
self.labvalue.move(140,120)
self.labvalue.setAlignment(Qt.AlignLeft)
self.labvalue.resize(120,20)


#Target

self.lab_target = QLabel('Target :', self)
self.lab_target.setAlignment(Qt.AlignRight)
self.lab_target.move(60,150)
self.lab_target.resize(50,20)

self.txttarget = QLineEdit(self)
self.txttarget.move(140,148)


#start button
self.btnstart = QPushButton('Start', self)
self.btnstart.move(140,180)
self.btnstart.clicked.connect(self.get_amount)

#Stop button
#self.btnstop = QPushButton('Stop', self)
#self.btnstop.move(220,180)
#self.btnstop.clicked.connect(self.stopM)
self.show()


def on_refresh(self):
#element = WebDriverWait(App.driver, 1000).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='nice-name']")))
element = App.driver.find_elements_by_xpath("//*[@class='nice-name']")
self.comsegment.clear()
for elemt in element:
self.comsegment.addItem(elemt.text)

def get_amount(self):
seg = str(self.comsegment.currentText())
Seg_Clk = seg.split()

element_order = App.driver.find_element_by_xpath("//*[@id='app']/div[1]/div/div[2]/div[1]/a[2]")
element_order.click()

element = App.driver.find_elements_by_xpath("//*[@class='info']")
App.m_blnLooping=True
StopScript = False
while App.m_blnLooping==True:
if StopScript == False:
for elemt in element:
details = str(elemt.text)
if details.find(seg) > -1:
amt = details.split()
#print('Found - ' + amt[-1])
self.labvalue.setFocus()
self.labvalue.setText(amt[-1])
QCoreApplication.processEvents()
cur_amt = float(amt[-1])
trgt_amt = float(self.txttarget.text())
if (self.comoption.currentText() == "Buy" and cur_amt >= trgt_amt and trgt_amt != 0 ):
element1 = App.driver.find_elements_by_xpath("//*[@class='tradingsymbol']")

for each_element in element1:
if str(Seg_Clk[0]) == str(each_element.text)[:len(str(Seg_Clk[0]))]:
ActionChains(App.driver).move_to_element(each_element).perform()

while True:
try:
element2 = App.driver.find_elements_by_xpath("//*[@class='context-menu-button-wrap']")
break
except ValueError:
print('Vaiting for element!')
for each_element2 in element2:
each_element2.click()

while True:
try:
element3 = App.driver.find_elements_by_xpath("//*[@class='icon icon-exit']")
break
except ValueError:
print('Vaiting for element!')
for each_element3 in element3:
each_element3.click()
while True:
try:
element4 = App.driver.find_elements_by_xpath("//*[@id='app']/div[2]/div/div/div/div/div/div/div[3]/div/button[1]/span")
break
except ValueError:
print('Vaiting for element!')
for each_element4 in element4:
each_element4.click()
print("Buy target achieved")
break
if (self.comoption.currentText() == "Sell" and cur_amt <= trgt_amt and trgt_amt != 0 ):
element1 = App.driver.find_elements_by_xpath("//*[@class='tradingsymbol']")

for each_element in element1:
if str(Seg_Clk[0]) == str(each_element.text)[:len(str(Seg_Clk[0]))]:
ActionChains(App.driver).move_to_element(each_element).perform()
while True:
try:
element2 = App.driver.find_elements_by_xpath("//*[@class='icon icon-ellipsis']")
break
except ValueError:
print('Vaiting for element!')
for each_element2 in element2:
each_element2.click()
while True:
try:
element3 = App.driver.find_elements_by_xpath("//*[@class='icon icon-exit']")
break
except ValueError:
print('Vaiting for element!')
for each_element3 in element3:
each_element3.click()
while True:
try:
element4 = App.driver.find_elements_by_xpath("//*[@class='button-orange']")
break
except ValueError:
print('Vaiting for element!')
for each_element4 in element4:
each_element4.click()
print("Sell target achieved")
StopScript = True


if msvcrt.kbhit():
if ord(msvcrt.getch()) == 27:
break

else:

break

#def stopM(self):
# App.m_blnLooping = False
# print("Tool Stopped")

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()

sys.exit(app.exec_())


Comments

Popular posts from this blog

Python - PyQt5 set Background image

import sys from PyQt5.QtCore import QSize from PyQt5.QtGui import QImage, QPalette, QBrush from PyQt5.QtWidgets import * class MainWindow ( QWidget ): def __init__ ( self ): QWidget. __init__ ( self ) self .setGeometry( 100 , 100 , 300 , 200 ) oImage = QImage( "test.jpg" ) sImage = oImage.scaled(QSize( 300 , 200 )) # resize Image to widgets size palette = QPalette() palette.setBrush( 10 , QBrush(sImage)) # 10 = Windowrole self .setPalette(palette) self .show() if __name__ == "__main__" : app = QApplication(sys.argv) oMainwindow = MainWindow() sys.exit(app.exec_())

pymsgbox - python package for message box

#This tutorial for to get a confirmation from the user by promting window #Python package "pymsgbox" needs to be install before run this below code #To install "pymsgbox" package go to command prompt and type in "PIP3 INSTALL pymsgbox" import pymsgbox #Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on. replyV = pymsgbox.confirm( text = 'Please login your application and click on on okay' , title = 'Login Confirmation' , buttons =[ 'OK' , 'Cancel' ]) print (replyV) #Displays a simple message box with text and a single OK button. Returns the text of the button clicked on. replyV = pymsgbox.alert( text = '' , title = '' , button = 'OK' ) print (replyV) #Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked. replyV1 = pyms