selenium python script is malfunctioning (Python Omagle Bot Script) - python

i am programming a simple omagle bot to learn more about the selenium.
what my scrips should be doing?
1.open the Omegle site, write some interest and press on the text button [this part is working]
2.it should type the text I defined it to text and then click on Esc button and then repeat this thing properly [this part is partially working]
Below is my script.
import random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Settings
tags = ['test']
browser = webdriver.Chrome()
print(">>Opening Browser window : ")
browser.get("https://www.omegle.com/")
print(">>Opening Site : ")
time.sleep(random.randint(2, 4))
print(">>loading page : ")
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
text_area = browser.find_element_by_class_name("topicplaceholder")
text_area.click()
input = browser.find_element_by_class_name("newtopicinput")
for i in tags:
input.send_keys(i)
print(">>Tag Entered > " + i)
input.send_keys(Keys.RETURN)
time.sleep(random.randint(1, 3))
browser.find_element_by_xpath("//img[#id='textbtn']").click()
print("opening a new chat : ")
i = 0
while i <= 50:
try:
time.sleep(2)
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[1]/div[1]/div/div[4]/div/div/img").click()
print("clicked Next chat button")
except:
try:
time.sleep(10)
time.sleep(3)
browser.find_element_by_xpath("//button[#class='disconnectbtn']").click()
print("ESCAPE pressed ")
print("waiting for 10 sec")
# Here messages add as manny as you want
browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/table/tbody/tr/td[2]/div/textarea").send_keys(
"Hey")
print("hy sent")
browser.find_element_by_xpath("//button[#class='sendbtn']").click()
time.sleep(5)
browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/table/tbody/tr/td[2]/div/textarea").send_keys(
"How are you?")
print("how are u sent")
browser.find_element_by_xpath("//button[#class='sendbtn']").click()
time.sleep(10)
browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]/table/tbody/tr/td[2]/div/textarea").send_keys(
"i am steve.")
print("i am steve")
browser.find_element_by_xpath("//button[#class='sendbtn']").click()
time.sleep(5)
i += 1
print(">Number Of messages send : ", str(i))
except:
print("pass")
try:
browser.find_element_by_xpath("/html/body/div[5]/div/div/div[1]/div[1]/div/div[6]/div/div/img").click()
print("clicked Next chat button")
except:
browser.find_element_by_xpath("//button[#class='disconnectbtn']").click()
print("ESCAPE pressed ")
browser.find_element_by_xpath("//button[#class='disconnectbtn']").click()
print("ESCAPE pressed ")

Related

Pyautogui Randomize Clicks locateonscreen and moveto

Hello I want to Randomize Clicks inside Pyautogui if it found a locateonscreen image or if it found pixelmatch color
so i tryed something but i cant check it becorse of the script is only use my part of code after other actions bevore
i have no idea to try only this function
i tried
def DisclaimerCheckAndClick():
try:
# Diclaimer 1
print("locate DisclaimerBingAccept01.png")
sleep(1)
x,y = locateCenterOnScreen("DisclaimerBingAccept01.png",region=(10,400,920,630), confidence=0.7)
click(x,y)
print("clicked DisclaimerBingAccept01.png",(x,y))
sleep(5)
pyautogui.hotkey('f5')
print("hotkey('f5') pressed..")
print("sleep(10)")
sleep(10)
ClickThirdTab()
# Doesn´t work for bing
#try:
#x,y = locateCenterOnScreen("BingSearchInputfieldSymbol.png",region=(10,160,920,630), confidence=0.7)
#pyautogui.moveTo(x,y,0.5)
#sleep(1)
#click(x,y)
#sleep(0.5)
#click(x,y)
#print("clicked BingSearchInputfieldSymbol.png",(x,y))
#except:
#print("BingSearchInputfieldSymbol.png not found")
except:
try:
# Diclaimer 2
print("locate DisclaimerGoogleAccept01.png")
sleep(1)
x,y = locateCenterOnScreen("DisclaimerGoogleAccept01.png",region=(10,400,920,630), confidence=0.7)
click(x,y)
print("clicked DisclaimerGoogleAccept01.png",(x,y))
sleep(5)
pyautogui.hotkey('f5')
print("hotkey('f5') pressed..")
print("sleep(15)")
sleep(15)
try:
x,y = locateCenterOnScreen("GoogleSearchInputfieldSymbol.png",region=(10,160,920,630), confidence=0.7)
pyautogui.moveTo(x,y,0.5)
sleep(1)
click(x,y)
print("clicked GoogleSearchInputfieldSymbol.png",(x,y))
pass
except:
print("GoogleSearchInputfieldSymbol.png not found")
I Try to Randomize this Disclaime Clicker script i found this :
DisclaimerYoutubeAccept01 = locateOnScreen('DisclaimerYoutubeAccept01.png',region=(10,400,920,630), confidence=0.7)
if Bank is not None:
pyautogui.moveTo(randomClick(DisclaimerYoutubeAccept01))
click()
print("clicked DisclaimerYoutubeAccept01.png",(DisclaimerYoutubeAccept01))
this isnt working so i tryed
DisclaimerYoutubeAccept01 = locateOnScreen('DisclaimerYoutubeAccept01.png',region=(10,400,920,630), confidence=0.7)
pyautogui.moveTo(randomClick(DisclaimerYoutubeAccept01))
click()
print("clicked DisclaimerYoutubeAccept01.png",(DisclaimerYoutubeAccept01))
this is my Def for Click
#Clicks location at x,y
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.1) #This pauses the script for 0.1 seconds
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
and this for the RandomCLICK(box)
def randomClick(box):
x_click = int(random.uniform(box.left, box.left+box.width))
y_click = int(random.uniform(box.top, box.top+box.height))
return (x_click, y_click)
but i cant check if it works script started but i cant check if this is working becorse the check of Disclaimer will only trigger if many things before are tryed
so what you think?

selenium click() method doesn't work after perfectly working a couple of hours before

I'm using selenium to like automatically some pictures. So the script searches for a word, clicks on the first picture, locates the like button then clicks on it.
The click button works to click on the picture but not to like it... I didn't change the identifier, so the class name is perfectly fine. I don't where the problem could come.
Here's my code :
'''
class Interact(Browser):
#click on the firt picture in the page
def firstpic_click(self):
time.sleep(2)
first = self.browser.find_element_by_class_name("kIKUG")
first.click()
#likes curent picture
def like_pic(self):
time.sleep(2)
like = self.browser.find_element_by_class_name("fr66n")
soup = bs(like.get_attribute('innerHTML'),'html.parser')
if (soup.find('svg')['aria-label'] == 'Like'):
like.click()
time.sleep(2)
#returns and clicks on next picture if any
def next_picture(self):
time.sleep(2)
try:
# nex = browser.find_element_by_xpath('//svg[#aria-label="Next"]')
next = self.browser.find_elements_by_class_name("wpO6b ")
soups = [bs(nextt.get_attribute('innerHTML'),'html.parser') for nextt in next]
for i in range(len(soups)):
#print(soups[i])
if (soups[i].find('svg')['aria-label'] == 'Next'):
next[i].click()
return next[i]
#nex = self.browser.find_element_by_xpath('//button[#class="wpO6b "]')
#time.sleep(1)
#return nex
except selenium.common.exceptions.NoSuchElementException:
return 0
#liking all the next pictures if any
def continue_liking(self):
while(True):
next_el = self.next_picture()
if next_el != False:
self.like_pic()
time.sleep(2)
next_el.click()
time.sleep(2)
else:
print("not found")
break
def word_search(self, search=1):
# word = input("what?")
word = "lol"
#search is the method of search
#looking for word in search box
if search == 0:
search_box = self.browser.find_element_by_xpath("//input[#aria-label='Search Input']")
search_box.send_keys("#"+word)
time.sleep(2)
#search_box.send_keys(Keys.RETURN)
#search_box.send_keys(Keys.RETURN)
search_box.submit()
time.sleep(5)
#type the website directly
if search == 1:
self.browser.get("https://www.instagram.com/explore/tags/" + word)
def liking_pictures(browser0):
browser0.implicitly_wait(5)
browser = Interact(browser0)
browser.word_search()
browser.firstpic_click()
browser.like_pic()
browser.next_picture()
browser.continue_liking()
time.sleep(10)
if __name__ == '__main__':
with browse() as browser0:
#unsubscribing(browser0)
liking_pictures(browser0)
'''
Thank you

Unclickable button in selenium

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(r'chromedriver.exe', options=chrome_options)
url = 'https://rarible.com/connect'
b = 1
def main():
driver.get(url)
input('Login..(Press ENTER when finsihed)')
sleep(1)
while driver.current_url == "https://rarible.com/":
ts_href = '/html/body/div[1]/div[2]/div[2]/div[2]/div/div/div/div[4]/div[2]/div/div[1]/div[1]/div/div/div[' \
'1]/div[1]/div/div[3]/a'
href = driver.find_element(By.XPATH, ts_href).get_attribute('href')
driver.get(href)
sleep(2)
followers = '/html/body/div/div[2]/div[2]/div[2]/div[2]/div/div/div/div[1]/div[5]/div/button[1]/span[2]'
driver.find_element(By.XPATH, followers).click()
sleep(3)
# buttons = driver.find_elements(By.XPATH, '//button[normalize-space()="Follow"]')
def butts():
global b
fbtn = f'/html/body/div/div[1]/div/div[2]/div/div[2]/div/div/div/div[{b}]/div/div/div[3]/button'
buttons = driver.find_element(By.XPATH, fbtn)
print(f'BUTTON {b} TEXT (FOLLOW/UNFOLLOW): {buttons.text}')
if buttons.text == "Follow":
buttons.click()
b += 1
sleep(1)
butts()
elif buttons.text == "Unfollow":
b += 1
butts()
butts()
print('All set here, onto the next one...')
else:
driver.get('https://rarible.com/')
if __name__ == '__main__':
main()
I cannot get it to click the follow buttons.
I Can't find an iframe that they are hiding in, or any other type of javascript voodoo being done but i am not the most experienced. Which is why i come to you seeking guidance.
The line where you define followers wasn't working for me so I changed it to
followers = '//button[#datamarker="root/appPage/address/profile/followingLinks/followers"]'
Trying to figure out how to get the butts() loop to run, but I don't have any followers on rarible so it's kind of hard to test. However, putting these lines of code in at the end of "if buttons.text == "Follow": before butts() is called again might work.
scroll_div = driver.find_element(By.XPATH, '/html/body/div/div[1]/div/div[2]/div/div[2]/div/div/div')
scroll_div.send_keys(Keys.ARROW_DOWN)
It's not actually an iframe. The solution has something to do with scrolling through the follow buttons

How to stop or pause pyautogui at any moment that I want?

I am building some macro program using pyautogui.
Unfortunately I am not able to stop for-loop so sometimes it takes too much time until for-loop end.
Is there any way to stop the program at any moment I want? or I just wait until program end.
below is my code
CURRENT_DIR = os.getcwd()
list = os.path.join(CURRENT_DIR,'BOM_list.xlsx')
df = pd.read_excel(list)
for i in df['MLFB'].index:
MLFB = df.loc[i, 'MLFB']
print(MLFB)
a = pyautogui.locateCenterOnScreen('a_material.png')
print(a)
pyautogui.moveTo(a)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(MLFB)
b = pyautogui.locateCenterOnScreen('b_execute.png')
print(b)
pyautogui.moveTo(b)
pyautogui.click()
time.sleep(2.5)
pyautogui.keyDown('alt')
pyautogui.press('y')
pyautogui.press('t')
pyautogui.press('a')
pyautogui.press('i')
pyautogui.keyUp('alt')
time.sleep(2)
pyautogui.press('down')
pyautogui.typewrite(['enter'])
time.sleep(2)
c = pyautogui.locateCenterOnScreen('c_Directory.png')
pyautogui.moveTo(c)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(CURRENT_DIR)
pyautogui.click()
time.sleep(1.5)
d = pyautogui.locateCenterOnScreen('d_Filename.png')
pyautogui.moveTo(d)
pyautogui.moveRel(350, 0)
pyautogui.click()
pyautogui.keyDown('ctrl')
pyautogui.press('left')
pyautogui.keyUp('ctrl')
pyautogui.typewrite(MLFB)
time.sleep(0.5)
pyautogui.typewrite(['enter'])
time.sleep(2)
e = pyautogui.locateCenterOnScreen('e_go_back.png')
pyautogui.moveTo(e)
pyautogui.click()
time.sleep(2)
PyAutoGUI has a built in failsafe to terminate the program at any time. Just move your mouse to the top left corner of your main monitor where your x, y values would be 0, 0.
Typing print(pyautogui.FAILSAFE) should return True, telling us the failsafe is on. You could also disable it if it's getting in the way of your program by setting it to pyautogui.FAILSAFE = False
Looking through your code, you could save some space by using hotkey() when you want to press more than one key at a time:
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
Is the same as:
pyautogui.hotkey('ctrl', 'a')
You could also check out threading which allows you to run more than one process at a time.
The following code will have an example main program running and when the Esc key is pressed, the main program will pause and the user is prompted if they want to continue or not.
import time
from threading import Thread
from pynput import keyboard
def exit_program():
def on_press(key):
if str(key) == 'Key.esc':
main.status = 'pause'
user_input = input('Program paused, would you like to continue? (y/n) ')
while user_input != 'y' and user_input != 'n':
user_input = input('Incorrect input, try either "y" or "n" ')
if user_input == 'y':
main.status = 'run'
elif user_input == 'n':
main.status = 'exit'
exit()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
def main():
main.status = 'run'
while True:
print('running')
time.sleep(1)
while main.status == 'pause':
time.sleep(1)
if main.status == 'exit':
print('Main program closing')
break
Thread(target=main).start()
Thread(target=exit_program).start()

Firefox headless mode with Selenium: why does it remember old access?

I'm trying to make up a system in order to automate sign-in procedure on booking.com.
What I want to accomplish is that when I visit the following page: https://join.booking.com/?lang=it , the browser have to show me the sign-in form as I was visiting it for the first time.
Unfortunately it doesn't happen, somehow Firefox remembers that I have already done something on this page and show me the "continue to register" page. I read that selenium always has a fresh start, I have disabled cache memory, form auto-fill but still I can't get it done.
Any suggestions? Maybe some Firefox preference should be set, like cache memory ecc...
Working with python 2.7.9, selenium 3.141.0 and geckodriver 0.26.0
import time
import sys
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def initialize_driver():
options = Options()
options.headless = True
options.add_argument("--private")
print(options)
driver = webdriver.Firefox(executable_path='/Users/giovanni/Documents/IA_beta_v0.0.0/tools/geckodriver', options=options)
try:
driver.get("https://www.google.com")
print("Driver successfully initialized\n")
except:
print("Error while initializing driver\n")
return driver
def close_driver(driver):
try:
driver.close()
print("Driver closed correclty\n")
except:
print("An error occured when trying to shut down driver\n")
def new_registration():
print("Enter name: ")
name = raw_input()
print("Enter surname: ")
surname = raw_input()
print("Enter email: ")
email_address = raw_input()
print("\nPlease check the information you have entered:\n")
print("Name = %s;\n" %name)
print("Surname = %s;\n" %surname)
print("Email address = %s;\n" %email_address)
print("Are these information correct?(y/n)\n")
user_answer = raw_input()
if user_answer == 'y':
print("Proceeding with entablishing connection with Booking.com\n")
elif user_answer == 'n':
print("What information would you like to change?\n")
print("\t-name;\n")
print("\t-surname;\n")
print("\t-email;\n")
user_answer = raw_input()
if user_answer == 'name':
print("You have choose to modify the name for the registration\n")
name = substitute_info_registration(1,name)
print("\nNew name is %s\n" %name)
elif user_answer == 'surname':
print("You have choose to modify the surname for the registration\n")
surname = substitute_info_registration(2,surname)
print("\nNew name is %s\n" %surname)
elif user_answer == 'email':
print("You have choose to modify the email address for the registration\n")
email_address = substitute_info_registration(3,email_address)
print("\nNew name is %s\n" %email_address)
else:
print("Wrong input. Please enter one of the three options\n")
else:
print("Wrong input. Please enter one of the two options\n")
booking_registration_procedure(name,surname,email_address)
def substitute_info_registration(flag,info):
if flag == 1:
print("Current name is %s. Which is going to be the new name? " %info)
user_answer = raw_input()
print("New name is %s.\n" %user_answer)
elif flag == 2:
print("Current surname is %s. Which is going to be the new surname? " %info)
user_answer = raw_input()
print("New surname is %s.\n" %user_answer)
elif flag == 3:
print("Current email address is %s. Which is going to be the new email address? " %info)
user_answer = raw_input()
print("New email address is %s.\n" %user_answer)
return user_answer
def booking_registration_procedure(name,surname,email_address):
print("Initializing driver...\n")
firefox = initialize_driver()
#STEP 1
firefox.get('https://join.booking.com/?lang=it')
#source = firefox.page_source
try:
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page.jpg')
print("Screenshot taken correctly\n")
except:
print("Can't take first screenshot\n")
try:
name_surname_form = firefox.find_element_by_id('ultranet_label_input_0')
name_surname_form.send_keys(name + " " + surname)
email_address_form = firefox.find_element_by_id('ultranet_label_input_1')
email_address_form.send_keys(email_address)
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page_after_filling_form.jpg')
except:
print("Can't fill form with name, surname and email address\n")
close_driver(firefox)
exit(1)
try:
continue_button = firefox.find_elements_by_name('save')
print continue_button
continue_button[0].click()
time.sleep(2)
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page_after_clicking_button.jpg')
except:
print("Can't click continue button\n")
close_driver(firefox)

Categories

Resources