i am making a whatsapp bot for my friends birthday i want to bombard him with messages :) ,
can u please help me in solving this problem :) ?
i have tried replacing \n with \r\n but was unable to simulate shift+enter
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
import socket
import time
handl=open('message.txt','r')
message_text=handl.read().replace('\n','\r\n')
no_of_message=1
filename='contacts.txt'
handle = open(filename,'r')
moblie_no_list=list() # list of phone number can be of any length
for number in handle:
if len(number)==12:
moblie_no_list.append(number)
elif len(number)==13:
moblie_no_list.append(number.replace('+',''))
elif len(number) ==10:
number='91'+number
moblie_no_list.append(number)
else:
pass
def element_presence(by,xpath,time):
element_present = EC.presence_of_element_located((By.XPATH, xpath))
WebDriverWait(driver, time).until(element_present)
def is_connected():
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
return True
except :
is_connected()
driver = webdriver.Firefox()
driver.get("http://web.whatsapp.com")
time.sleep(10) #wait time to scan the code in second
def send_whatsapp_msg(phone_no,text):
driver.get("https://web.whatsapp.com/send?phone=
{}&source=&data=#".format(phone_no))
try:
driver.switch_to_alert().accept()
except:
pass
try:
element_presence(By.XPATH,'//*
[#id="main"]/footer/div[1]/div[2]/div/div[2]',30)
txt_box=driver.find_element(By.XPATH , '//*
[#id="main"]/footer/div[1]/div[2]/div/div[2]')
global no_of_message
for x in range(no_of_message):
txt_box.send_keys(text)
txt_box.send_keys("\n")
except :
print("invailid phone no :"+str(phone_no))
for moblie_no in moblie_no_list:
try:
send_whatsapp_msg(moblie_no,message_text)
except Exception as e:
time.sleep(10)
is_connected()
I Expected Sending Multiline Messages But It Splits Em Into Single Message each .
txt_box.send_keys(Keys.SHIFT,'\n')
Here's What I Did To Solve The Question
Keys.Shift Will Manipulate Press Of Shift Key Followed By '\n' Carriage Return.
Link To Complete Code On Github
Complete Solved Code Is Here :) :
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
import socket
import time
handl=open('message.txt','r', encoding="utf8")
message_text=handl.read()
messages=message_text.split('\n')
print(messages)
no_of_message=1
filename='contacts.txt'
handle = open(filename,'r')
moblie_no_list=list() # list of phone number can be of any length
for number in handle:
if len(number)==12:
moblie_no_list.append(number)
elif len(number)==13:
moblie_no_list.append(number.replace('+',''))
elif len(number) ==10:
number='91'+number
moblie_no_list.append(number)
else:
pass
def element_presence(by,xpath,time):
element_present = EC.presence_of_element_located((By.XPATH, xpath))
WebDriverWait(driver, time).until(element_present)
def is_connected():
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
return True
except :
is_connected()
driver = webdriver.Firefox()
driver.get("http://web.whatsapp.com")
time.sleep(10) #wait time to scan the code in second
def send_whatsapp_msg(phone_no,text):
driver.get("https://web.whatsapp.com/send?phone={}&source=&data=#".format(phone_no))
try:
driver.switch_to_alert().accept()
except:
pass
try:
element_presence(By.XPATH,'//*[#id="main"]/footer/div[1]/div[2]/div/div[2]',30)
txt_box=driver.find_element(By.XPATH , '//*[#id="main"]/footer/div[1]/div[2]/div/div[2]')
global messages
for message in messages:
txt_box.send_keys(message)
txt_box.send_keys(Keys.SHIFT,'\n')
txt_box.send_keys("\n")
except :
print("invailid phone no :"+str(phone_no))
for moblie_no in moblie_no_list:
try:
send_whatsapp_msg(moblie_no,message_text)
except Exception as e:
time.sleep(10)
is_connected()
Related
the code below for sending text messages but how to replace to attach PDF file and send it via WhatsApp
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, UnexpectedAlertPresentException, NoAlertPresentException
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep
from urllib.parse import quote
from sys import platform
options = Options()
if platform == "win64":
options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
f = open("message.txt", "r")
message = f.read()
f.close()
print("##########################################################")
print('This is your message\n\n')
print(message)
print("##########################################################")
message = quote(message)
numbers = []
f = open("numbers.txt", "r")
for line in f.read().splitlines():
if line != "":
numbers.append(line)
f.close()
total_number=len(numbers)
print("##########################################################")
print('\nWe found ' + str(total_number) + ' numbers in the file')
print("##########################################################")
print()
delay = 30
driver = webdriver.Chrome(ChromeDriverManager().install())
print('Once your browser opens up sign in to web whatsapp')
driver.get('https://web.whatsapp.com')
input("Press ENTER after login into Whatsapp Web and your chats are visiable .")
for idx, number in enumerate(numbers):
number = number.strip()
if number == "":
continue
print('{}/{} => Sending message to {}.'.format((idx+1), total_number, number))
try:
url = 'https://web.whatsapp.com/send?phone=' + number + '&text=' + message
sent = False
for i in range(3):
if not sent:
driver.get(url)
try:
click_btn = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CLASS_NAME , '_4sWnG')))
except Exception as e:
print(f"Something went wrong..\n Failed to send message to: {number}, retry ({i+1}/3)")
print("Make sure your phone and computer is connected to the internet.")
print("If there is an alert, please dismiss it.")
input("Press enter to continue")
else:
sleep(1)
click_btn.click()
sent=True
sleep(3)
print('Message sent to: ' + number)
except Exception as e:
print('Failed to send message to ' + number + str(e))
I am trying to search through websites to determine with certain items are in stock. I want this to search the site, find out if the item is "In stock" or not and notify the user of the found information. I can get most of the code to run but this continually returns empty lists. (I tried in BeautifulSoup4 as well as Selenium with the same outcome. Both versions below).What am I missing? Any help would be greatly appreciated!
#selenium version
import os
import string
import subprocess
import traceback
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def webscan():
driver = webdriver.Chrome('/usr/lib/python3/dist-packages/selenium/webdriver/chrome/chromedriver')
#driver.maximize_window()
driver.get("https://www.amazon.com/GIGABYTE-GeForce-Windforce-Graphics-GV-N207SWF3OC-8GD/dp/B07WN6RVHH/ref=sr_1_11?crid=OOF3E7T9W54&dchild=1&keywords=graphics+card&qid=1630118746&sprefix=graphi%2Caps%2C190&sr=8-11")
#wait for the page to load fully
time.sleep(5)
status = driver.find_element_by_class('a-size-medium a-color-state')
ps5_avail = status
print(ps5_avail)
if ps5_avail == "Currently unavailable":
print("Sorry. Still not in stock...")
elif ps5_avail == "Temporarily Out of Stock":
print("Sorry. Still not in stock...")
elif ps5_avail == "In stock soon.":
print("sorr. Still not in stock...")
else:
print("Go NOW!!!!!")
driver.close()
user_input = (input("Want a PS5?"))
if user_input == 'yes':
webscan()
print('scan is done')
####################################################################
#beautifulsoup version
import requests
from bs4 import BeautifulSoup
url = 'https://www.amazon.com/GIGABYTE-GeForce-Windforce-Graphics-GV-N207SWF3OC-8GD/dp/B07WN6RVHH/ref=sr_1_11?crid=OOF3E7T9W54&dchild=1&keywords=graphics+card&qid=1630118746&sprefix=graphi%2Caps%2C190&sr=8-11'
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.parser')
text = soup.find_all(string='In Stock')
if text == True:
print("Out of Stock")
else:
print("Get it!")
You should use this css selector instead :
Code :
driver.get("https://www.amazon.com/GIGABYTE-GeForce-Windforce-Graphics-GV-N207SWF3OC-8GD/dp/B07WN6RVHH/ref=sr_1_11?crid=OOF3E7T9W54&dchild=1&keywords=graphics+card&qid=1630118746&sprefix=graphi%2Caps%2C190&sr=8-11")
#wait for the page to load fully
time.sleep(5)
lngth = len(driver.find_elements(By.CSS_SELECTOR, "span.a-size-medium.a-color-state"))
print("value of lngth", lngth)
try:
if len(driver.find_elements(By.CSS_SELECTOR, "span.a-size-medium.a-color-state")) > 0:
print("Inside if")
status = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div#availability span"))).text
print(status)
else:
print("Looks like element was not found.")
except:
print("Something went wrong")
pass
Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
I use that script for WhatsApp integration with my website in python.
Why My that Script is not working can you please check here in contact i maintain my contactfile and when use ipdb for trace code it show me error in line 30.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome('./chromedriver')
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 600)
with open("contact") as f:
for line in f:
try:
name = (line.rstrip('\n'))
text = """Hello {}, My name is Rhevin
Have a good day :)
""".format(name)
print 'Harish'
inp_xpath_search = "//input[#title='Search or start new chat']"
input_box_search = wait.until(EC.presence_of_element_located((
By.XPATH, inp_xpath_search)))
print '################',input_box_search
input_box_search.send_keys(name + Keys.ENTER)
#x_arg_contact = '//div[#class="chat-title"]'
x_arg_contact = '//span[contains(#title,' + name + ')]'
input_box_contact = wait.until(EC.presence_of_element_located((
By.XPATH, x_arg_contact)))
print '-------------------',input_box_contact
inp_xpath = "//div[#contenteditable='true']"
input_box = wait.until(EC.presence_of_element_located((
By.XPATH, inp_xpath)))
print '+++++++++++++++++++++++',input_box
input_box.send_keys(text + Keys.ENTER)
print '==============================='
time.sleep(5)
print("send")
except:
print("error")
Im trying to translate user comments from tripadvisor.
My code :-
1.]Selects only portuguese comments( from language dropdown),
2.]Then expands each of the comments,
3.]Then saves all these expanded comments in a list
4.]Then translates them into english & prints on screen
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
com_=[] # To save translated comments
expanded_comments=[] # To save expanded comments
driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe")
driver.maximize_window()
def expand_reviews(driver):
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
def save_comments(driver):
expand_reviews(driver)
# SELECTING ALL EXPANDED COMMENTS
expanded_com_elements=driver.find_elements_by_class_name("entry")
time.sleep(3)
for i in expanded_com_elements:
expanded_comments.append(i.text)
# SELECTING ALL GOOGLE-TRANSLATOR links
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
# NOW PRINTING TRANSLATED COMMENTS
for i in gt:
try:
driver.execute_script("arguments[0].click()",i)
#i.click().perform()
com=driver.find_element_by_class_name("ui_overlay").text
com_.append(com)
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click().perform()
time.sleep(5)
except Exception as e:
pass
#print e
for i in range(282):
page=i*10
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or"+str(page)+"-TAP-Portugal#REVIEWS"
driver.get(url)
wait = WebDriverWait(driver, 10)
if i==0:
# SELECTING PORTUGUESE COMMENTS ONLY # Run for one time then iterate over pages
try:
langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[#class='languageList']//li[normalize-space(.)='Portuguese first']").click()
time.sleep(5)
except Exception as e:
print e
save_comments(driver)
================ERROR=================
expanded_comments return empty list. Some comments get saved, some get skipped.
First page is saved properly (all comments expanded), but thereafter only first comment gets saved, without being expanded. But translated comments from all pages get saved properly in com_
I have changed your code and now it's working.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("./chromedriver.exe")
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#REVIEWS"
driver.get(url)
wait = WebDriverWait(driver, 10)
# SELECTING PORTUGUESE COMMENTS ONLY
#show_lan = driver.find_element_by_xpath("//div[#class='languageList']/ul/li[contains(text(),'Portuguese first')]")
try:
langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[#class='languageList']//li[normalize-space(.)='Portuguese first']").click()
time.sleep(5)
except Exception as e:
print e
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
# SELECTING ALL EXPANDED COMMENTS
expanded_com_elements=driver.find_elements_by_class_name("entry")
expanded_comments=[]
time.sleep(3)
for i in expanded_com_elements:
expanded_comments.append(i.text)
# SELECTING ALL GOOGLE-TRANSLATOR links
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
# NOW PRINTING TRANSLATED COMMENTS
for i in gt:
try:
driver.execute_script("arguments[0].click()",i)
#i.click().perform()
print driver.find_element_by_class_name("ui_overlay").text
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click().perform()
time.sleep(5)
except Exception as e:
pass
#print e
I am trying to do web scraping from http://www.gps-coordinates.net/ using selenium, and I have problem in 2 areas.
Google Autocomplete causes me to unable to click the 'get
coordinates' button. I tried to solve it but sometimes it still
doesnt work. ( Message: Element is not clickable at point (280, 17.800003051757812). Other element would receive the click )
Pop up indicates that there are no result available, but I still fail to handle the pop-up.
`
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import openpyxl
import xlsxwriter
import pyperclip
driver = ""
def setup():
global driver
driver = webdriver.Firefox()
driver.get("http://www.gps-coordinates.net/")
assert 'Google Map' in driver.title
def sele(address):
setup()
global driver
query = driver.find_element_by_id('address')
query.clear()
query.send_keys(address)
query.send_keys(Keys.RETURN)
driver.implicitly_wait(0.7)
query.send_keys(Keys.DOWN) #To solve in case there is autocomplete by Google
query.send_keys(Keys.RETURN)
button = driver.find_element_by_xpath("//*[#id='wrap']/div[2]/div[4]/div[1]/form[1]/div[2]/div/button")
button.click()
driver.implicitly_wait(0.7)
if EC.alert_is_present(): #If there is a popup, that means there is no result for the geocoding
alert=driver.switch_to_alert()
alert.accept()
latlong = ['Fail','Fail']
return latlong
else:
latraw = driver.find_element_by_id('latitude')
longraw = river.find_element_by_id('longitude')
latraw.send_keys(Keys.CONTROL,'A')
latraw.send_keys(Keys.CONTROL,'C')
lat = pyperclip.paste()
latraw.clear()
longraw.send_keys(Keys.CONTROL,'A')
longraw.send_keys(Keys.CONTROL,'C')
long = pyperclip.paste()
latraw.clear()
return [lat,long]
I solved my problem with this code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import openpyxl
import xlsxwriter
import pyperclip
driver = ""
def setup():
global driver
driver = webdriver.Firefox()
driver.get("http://www.gps-coordinates.net/")
assert 'Google Map' in driver.title
def sele(address):
global driver
query = driver.find_element_by_id('address')
query.clear()
query.send_keys(address)
query.send_keys(Keys.RETURN)
driver.implicitly_wait(0.7)
query.send_keys(Keys.DOWN) #To solve in case there is autocomplete by Google
query.send_keys(Keys.RETURN)
button = driver.find_element_by_xpath("//*[#id='wrap']/div[2]/div[4]/div[1]/form[1]/div[2]/div/button")
button.click()
driver.implicitly_wait(0.7)
try:
alert=driver.switch_to_alert()
alert.accept()
latlong = ['Fail','Fail']
return latlong
except Exception :
latraw = driver.find_element_by_id('latitude')
longraw = driver.find_element_by_id('longitude')
newquery = driver.find_element_by_id('address')
lat = latraw.get_attribute('value')
long = longraw.get_attribute('value')
query = newquery.get_attribute('value')
return [lat,long,query]
def wrapper(inputad,outputad,k):
InFile = openpyxl.load_workbook(inputad)
Sheet = InFile['Sheet1']
workbook = xlsxwriter.Workbook(outputad)
worksheet = workbook.add_worksheet()
TotalLength = Sheet.max_row
ProgressChecker = 0
for i in range(1, TotalLength +1):
ProgressChecker = ProgressChecker + 1
addtext = Sheet[i][k].value
try:
latlong = sele(addtext)
worksheet.write(i,0,addtext)
worksheet.write(i,1,latlong[0])
worksheet.write(i,2,latlong[1])
worksheet.write(i,2,latlong[2])
print("Progress: ", ProgressChecker, " out of " ,TotalLength)
except Exception :
worksheet.write(i,0,addtext)
worksheet.write(i,1,"Failure Inside Iteration")
print("Progress: ", ProgressChecker, " out of " ,TotalLength)
continue
complete = "complete"
return complete