monitor chrome tabs - python selenium - python

I'm writing a script where I need you to monitor the number of open tabs. The script reads a table and each information in the table opens a new tab in the browser. It turns out that in order not to have thousands of tabs open, I need the script to monitor the tabs to have only 3 open, when I close a tab I need to automatically open the next tab
def base_dados_processos(self):
try:
df = pd.read_excel('TABLE.xlsx')
self.num_proc = df['COLUM']
except Exception:
pg.alert(text='error', title='ERROR', button='OK')
self.chrome.quit()
def loop_pesquisa(self):
for PROCESSOS in zip(self.num_proc):
num_current_tabs = len(self.chrome.window_handles)
if num_current_tabs < 3:
pg.hotkey('ctrl', '1')
time.sleep(1)
self.chrome.get('https://stackoverflow.com/')
pg.write(str(test))
pg.press('enter')
time.sleep(3)
pg.press('tab', presses=26)
pg.press('enter')
time.sleep(1)
pg.press('enter')

To do this, just add a loop that monitors the guides, it can be as follows:
while len(self.chrome.window_handles) > 3:
time.sleep(0.5)
without your code:
def base_dados_processos(self):
try:
df = pd.read_excel('TABLE.xlsx')
self.num_proc = df['COLUM']
except Exception:
pg.alert(text='error', title='ERROR', button='OK')
self.chrome.quit()
def loop_pesquisa(self):
for PROCESSOS in zip(self.num_proc):
while len(self.chrome.window_handles) > 3:
time.sleep(0.5)
pg.hotkey('ctrl', '1')
time.sleep(1)
self.chrome.get('https://stackoverflow.com/')
pg.write(str(test))
pg.press('enter')
time.sleep(3)
pg.press('tab', presses=26)
pg.press('enter')
time.sleep(1)
pg.press('enter')

Related

auto-setting price for minted NFT collection on OpenSea

Im trying to sell minted NFT collection on OpenSea with this script:
# Set price
for i in range(10000): # See if it's there
try:
chrome.find_element(By.XPATH, '//input[#name="price"]')
break
except:
time.sleep(0.5)
chrome.find_element(By.XPATH, '//input[#name="price"]').send_keys(price + Keys.RETURN)
# Click sign
for i in range(10000):
try:
chrome.find_element(By.XPATH, '//button[text()="Sign"]')
break
except:
time.sleep(0.5)
chrome.find_element(By.XPATH, '//button[text()="Sign"]').click()
# scroll
chrome.find_element(By.XPATH, '//div[#data-testid="signature-request-scroll-button"]').click()
# waiting unblock button
time.sleep(1)
# sign
chrome.find_element(By.XPATH, '//button[text()="Sign"]').click()
and the script stuck when Metamask ask for sign transaction because of "scroll down" button

PySimpleGUI with Selenium

I've made a PySimpleGUI app with Selenium, it takes CSV values and puts them into a form and submits it, now however we need to send an input to the form.
So I added this:
[sg.Multiline(size=(30, 5), key='deposit')],
But how do I reference it in the send_keys function that I'm using currently:
...
mail_field.send_keys(line[13])
phone_field.send_keys(line[16])
deposit_field.send_keys('deposit') ?
submit.click()
Thought I'd try values['deposit'] but that doesnt work either
Entire code
import csv
import time
import threading
from selenium import webdriver
import PySimpleGUI as sg
import os
import sys
def resource_path(relative_path):
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def make_window(theme):
sg.theme('LightGrey')
menu_def = [['&Application', ['E&xit']],
['&Help', ['&About']]]
right_click_menu_def = [[], ['Exit']]
# Table Data
input_layout = [[sg.Menu(menu_def, key='-MENU-')],
[sg.Button("Open File", button_color=(
'white', 'dodgerblue'))],
[sg.Text('Chrome Version')],
[sg.OptionMenu(values=(
'96', '97', '98'), k='-OPTION MENU-', background_color='dodgerblue'), ],
[sg.Multiline(size=(30, 5), key='deposit')],
[sg.Button('Submit', button_color=('white', '#Ed1941'))]]
layout = [[sg.Text('Name', size=(35, 1), justification='center', font=(
"Helvetica", 16), relief=sg.RELIEF_RIDGE, k='-TEXT HEADING-', enable_events=True)]]
layout += [[sg.TabGroup([[sg.Tab('Setup CSV and Chrome Version', input_layout),
]], key='-TAB GROUP-', size=(400, 120))]]
return sg.Window('Name', layout, icon='icon.ico', right_click_menu=right_click_menu_def)
def main():
window = make_window(sg.theme('LightGrey'))
# This is an Event Loop
while True:
event, values = window.read(timeout=100)
# keep an animation running so show things are happening
if event not in (sg.TIMEOUT_EVENT, sg.WIN_CLOSED):
print('============ Event = ', event, ' ==============')
print('-------- Values Dictionary (key=value) --------')
for key in values:
print(key, ' = ', values[key])
if event in (None, 'Exit'):
print("[LOG] Clicked Exit!")
break
elif event == 'About':
print("[LOG] Clicked About!")
sg.popup('',
'Select CSV file',
'Select Chrome Version',
'Submit',
'')
elif event == 'Popup':
print("[LOG] Clicked Popup Button!")
sg.popup("You pressed a button!")
print("[LOG] Dismissing Popup!")
elif event == "Open File":
print("[LOG] Clicked Open File!")
csv_file_selected = sg.popup_get_file('Choose your file')
# sg.popup("You chose: " + str(folder_or_file))
# print("[LOG] User chose file: " + str(folder_or_file))
def run_selenium(window, file, driver):
with open(file, 'rt') as csv_file:
csv_reader = csv.reader(csv_file)
# -------------------------------------------------------------------------------
# Web Automation
driver = webdriver.Chrome(executable_path=driver)
driver.get('')
fname_field = driver.find_element_by_xpath('//*[#id="FIRSTNAME"]')
lname_field = driver.find_element_by_xpath('//*[#id="LASTNAME"]')
phone_field = driver.find_element_by_xpath('//*[#id="PHONE"]')
mail_field = driver.find_element_by_xpath('//*[#id="EMAIL"]')
deposit_field = driver.find_element_by_xpath('//*[#id="DEPOSIT"]')
submit = driver.find_element_by_xpath(
'//*[#id="sib-form"]/div[8]/div/button')
with open(file, 'rt', encoding='utf-8-sig') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
next(csv_reader)
for line in csv_reader:
time.sleep(3.0)
fname_field.send_keys(line[10])
lname_field.send_keys(line[11])
mail_field.send_keys(line[13])
phone_field.send_keys(line[16])
deposit_field.send_keys(text) //Here
submit.click()
# Not to update GUI in thread, but generate an event which will be processed in event loop.
window.write_event_value('Done', None)
def main():
# My GUI
window = make_window(sg.theme())
folder_or_file = None
cd97 = resource_path('./chromedriver97.exe')
cd98 = resource_path('./chromedriver98.exe')
# Using your path for all the drivers of all versions
paths = {
'97': cd97,
'98': cd98,
}
while True:
event, values = window.read(timeout=100)
# keep an animation running so show things are happening
if event not in (sg.TIMEOUT_EVENT, sg.WIN_CLOSED):
# print('============ Event = ', event, ' ==============')
# print('-------- Values Dictionary (key=value) --------')
for key in values:
print(key, ' = ', values[key])
if event in (None, 'Exit'):
# print("[LOG] Clicked Exit!")
break
elif event == 'About':
# print("[LOG] Clicked About!")
sg.popup('',
'Select CSV file',
'Select Chrome Version',
'Submit',
'')
elif event == 'Popup':
# print("[LOG] Clicked Popup Button!")
sg.popup("You pressed a button!")
# print("[LOG] Dismissing Popup!")
elif event == "Open File":
#print("[LOG] Clicked Open File!")
folder_or_file = sg.popup_get_file('Choose your file')
# sg.popup("You chose: " + str(folder_or_file))
#print("[LOG] User chose file: " + str(folder_or_file))
elif event == 'Submit':
version = values['-OPTION MENU-']
if folder_or_file is None or version not in paths:
# print("No CSV file selected or wrong Chrome version selected")
continue
# Using thread to avoid long time job will block and cause GUI no response
threading.Thread(target=run_selenium, args=(
window, folder_or_file, paths[version])).start()
# Disable Submit button to prevent submit again when threading
window['Submit'].update(disabled=True)
# print('[LOG] Run Selenium ...')
elif event == 'Done':
# Enable Submit button when thread done
window['Submit'].update(disabled=False)
# print('[LOG] End Selenium')
window.close()
main()
elif event == 'Submit': text=values['deposit'];...;threading.Thread(target=run_selenium, args=(window, folder_or_file, paths[version], text)).start();... and one more arguemnt text in def run_selenium(window, file, driver, text):
Answer by: Jason Yang. https://stackoverflow.com/users/11936135/jason-yang

How can I handle pyautogui screenshot error?

I'm trying to code "Keep what you are doing, when ss.png has seen on screen, do this instead" but it only prints None again and again. What should I do?
try:
image = gui.locateOnScreen("ss.png")
print(image)
except:
gui.click(296, 47, clicks=3, interval=0.25)
gui.press("enter")
time.sleep(2)
gui.click(499, 484, clicks=3, interval=0.25)
time.sleep(5)
gui.click(505, 585)
gui.press("enter")
time.sleep(5)
gui.click(133, 223)
time.sleep(2)
gui.click(477, 101)
time.sleep(3)
time.sleep(5)
gui.click(667, 376)
time.sleep(40)
gui.click(1225, 106)
time.sleep(2)
gui.click(1175, 269)
time.sleep(5)
counter = counter + 1

Python selenium Element not clickable since another element obscures it

I have the following code. There is a problem in the line with:
timePicker = browser.find_element_by_xpath('//*[#class="time hasTimepicker"]')
It raises this exception:
selenium.common.exceptions.ElementClickInterceptedException: Message: Element <input id="tp1594226550595" class="time hasTimepicker" type="text"> is not clickable at point (753,293) because another element <rect class="highcharts-background"> obscures it
I have already tried solutions which use 'wait', but there is a timeout exception. It seems the obstruction is permanent. I have also tried ActionChains, but it's not working either.
The element I am trying to click on is in this image:
The graph is the element obscuring the time picker at the top:
from time import sleep, time
from selenium import webdriver
from selenium.common.exceptions import \
NoSuchElementException, \
ElementClickInterceptedException, \
ElementNotInteractableException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", "C:/Users/USER/Documents/temp")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv")
print('opening browser')
browser = webdriver.Firefox(
executable_path='C:/Users/USER/Documents/Python Workspace/geckodriver/geckodriver.exe',
firefox_profile=fp
)
print('opening link')
browser.get('https://webtrader.binary.com/v2.2.8/main.html#historical-data')
def close_popup():
entrytime = time()
try:
currenttime = time()
if currenttime - entrytime >= 10:
return
close1 = browser.find_element_by_xpath('/html/body/div[3]/div[1]/div/button/span[1]')
except NoSuchElementException:
sleep(2)
close_popup()
try:
currenttime = time()
if currenttime - entrytime >= 10:
return
click_element(close1)
except UnboundLocalError:
currenttime = time()
if currenttime - entrytime >= 10:
return
sleep(2)
close_popup()
def click_element(element):
entrytime = time()
try:
currenttime = time()
if currenttime - entrytime >= 10:
return
element.click()
sleep(2)
except ElementClickInterceptedException:
currenttime = time()
if currenttime - entrytime >= 10:
return
sleep(2)
click_element(element)
except ElementNotInteractableException:
currenttime = time()
if currenttime - entrytime >= 10:
return
sleep(2)
click_element(element)
def resources():
try:
global res
res = browser.find_element_by_link_text('Resources')
res.click()
sleep(2)
except NoSuchElementException:
resources()
print('accessing Resources')
resources()
print()
#
#
def historical_data():
global res
try:
hd = browser.find_element_by_link_text('Historical Data')
sleep(2)
except ElementNotInteractableException:
sleep(2)
historical_data()
except NoSuchElementException:
sleep(2)
res.click()
historical_data()
try:
hd.click()
sleep(2)
except UnboundLocalError:
sleep(2)
historical_data()
# hd.click()
# sleep(2)
print('accessing Historical data')
historical_data()
maxWindow = browser.find_element_by_xpath('/html/body/div[8]/div[1]/div/a[3]/span')
browser.execute_script('arguments[0].click();', maxWindow)
sleep(2)
print('setting data type to 1 Tick')
while True:
try:
dt = browser.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[1]/span/span[1]')
break
except NoSuchElementException:
sleep(2)
dt.click()
sleep(2)
tick = browser.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[2]/div[1]/div[2]/span')
tick.click()
sleep(2)
#
while True:
try:
timePicker = browser.find_element_by_xpath('//*[#class="time hasTimepicker"]')
break
except NoSuchElementException:
sleep(2)
timePicker.click()
Try this instead:
while True:
try:
timePicker = browser.find_element_by_xpath('/html/body/div[8]/div[4]/input[2]')
break
except NoSuchElementException:
sleep(2)
timePicker.click()
Additionally, you import WebDriverWait, but don't use it. Try this, replace:
while True:
try:
dt = browser.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[1]/span/span[1]')
break
except NoSuchElementException:
sleep(2)
dt.click()
sleep(2)
tick = browser.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[2]/div[1]/div[2]/span')
tick.click()
sleep(2)
#
while True:
try:
timePicker = browser.find_element_by_xpath('//*[#class="time hasTimepicker"]')
break
except NoSuchElementException:
sleep(2)
timePicker.click()
with this:
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[1]/span/span[1]'))).click()
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[8]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[1]/div[2]/div[1]/div[2]/span'))).click()
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[8]/div[4]/input[2]'))).click()
You'll immediately notice its significantly faster, and cleaner. I'd replace all those while,try, and time.sleep() with WebDriverWait.

How to close selenium drivers while multiprocessing in python on command?

I wrote a python script that uses multiprocessing to open up four different windows and search a common query among them; I'm trying to find a way to close the drivers on command instead of calling driver.close() at the end of the function which would automatically close the drivers as soon as they have successfully spawned.
I would like to browse the windows for a bit and close them when I am finished.
Here's what my code looks like:
def main(hosts, inp):
driver = webdriver.Chrome(executable_path='./chromedriver')
driver.get(hosts)
if 'ebay' in driver.current_url:
print 'opened ebay'
search_box = driver.find_element_by_id('gh-ac')
search_box.clear()
search_box.send_keys(inp)
search_box.send_keys(Keys.RETURN)
elif 'google' in driver.current_url:
print 'opened google'
search_box = driver.find_element_by_id('gbqfq')
search_box.clear()
search_box.send_keys(inp)
search_box.send_keys(Keys.RETURN)
elif 'etsy' in driver.current_url:
print 'opened etsy'
search_box = driver.find_element_by_id('search-query')
search_box.clear()
search_box.send_keys(inp)
search_box.send_keys(Keys.RETURN)
elif 'amazon' in driver.current_url:
print 'opened amazon'
search_box = driver.find_element_by_id('twotabsearchtextbox')
search_box.clear()
search_box.send_keys(inp)
search_box.send_keys(Keys.RETURN)
else:
print "--NONE--"
# driver.close()
if __name__ == '__main__':
hosts = ["http://ebay.com", "https://www.google.com/shopping?hl=en", "http://etsy.com", "http://amazon.com"]
num_hosts = len(hosts)
inp = raw_input("What do you want to search?: ")
p = Pool(num_hosts)
partial_main = partial(main, inp=inp)
p.map(partial_main, hosts)
p.close()
p.join()
I would like to do something like this:
done = raw_input("Type 'done' when finished:" )
if done = 'done':
driver.close()
but just injected that into main gives me an EOF error

Categories

Resources