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))
Related
I encountered such a problem that I can not take a separate string from the file for each individual thread in multiprocessing. It turns out only to take a line of one line for all the threads at the same time.
In other words, I want to: First thread = take first line of file; Second thread = take second line of file, etc.
from multiprocessing import Pool
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import pyperclip
import time
from selenium.webdriver.common.by import By
import multiprocessing
password = "12345"
with open("Token.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
def get_data(url):
try:
service = Service(r"D:\pythonProject\Test\chromedriver\chromedriver.exe")
chrome_options = Options()
chrome_options.add_extension(
"metamask.crx")
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get(url=url)
time.sleep(5)
driver.switch_to.window(driver.window_handles[1])
driver.get("chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html")
time.sleep(2)
driver.switch_to.window(driver.window_handles[1])
driver.get("chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html")
time.sleep(2)
start_metamask_button = driver.find_element(By.XPATH,
'//*[#id="app-content"]/div/div[2]/div/div/div/button').click()
time.sleep(3)
import_wallet = driver.find_element(By.XPATH,
'//*[#id="app-content"]/div/div[2]/div/div/div[2]/div/div[2]/div[1]/button').click()
time.sleep(3)
agreed = driver.find_element(By.XPATH,
'//*[#id="app-content"]/div/div[2]/div/div/div/div[5]/div[1]/footer/button[2]').click()
time.sleep(3)
select_word_phrase = Select(
driver.find_element(By.XPATH, '//*[#id="app-content"]/div/div[2]/div/div/div[2]/form/div[1]/div[2]/select'))
select_word_phrase.select_by_visible_text('I have a 24-word phrase')
time.sleep(3)
search_elem = driver.find_element(By.XPATH, '//*[#id="import-srp__srp-word-0"]').click()
time.sleep(2)
pyperclip.copy(content)
print(content)
except Exception as ex:
print(ex)
finally:
driver.quit()
if __name__ == '__main__':
process_count = 3
url = 'chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/home.html'
urls_list = [url] * process_count
print(urls_list)
p = Pool(processes=process_count)
p.map(get_data, urls_list)
So I have been using python for twitter scraping using selenium driver. In my code most part of code is working, when I am only scraping a single tweet it's working. But when I am repeating the process for more than one tweet its not working. It is scrolling through the new tweets but not scraping anything. It is not saving anything. I have used this code : https://github.com/israel-dryer/Twitter-Scraper/blob/main/twitter-scraper-tut.ipynb
Please help me to correct the mistake in my code. Here is my code:
import time
import csv
from getpass import getpass
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Chrome
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.twitter.com/login')
driver.maximize_window()
time.sleep(5)
username = driver.find_element(by=By.XPATH, value='//input[#name="text"]')
username.send_keys('ABC')
username.send_keys(Keys.RETURN)
time.sleep(5)
password = driver.find_element(by=By.XPATH, value='//input[#name="password"]')
password.send_keys('XYZ')
password.send_keys(Keys. RETURN)
time.sleep(5)
search_input = driver.find_element(by=By.XPATH, value='//input[#aria-label="Search query"]')
# '//input[#aria-label-"Search query"]'
search_input.send_keys('#NEET')
search_input.send_keys(Keys.RETURN)
time.sleep(5)
driver.find_element(by=By.LINK_TEXT,value='Latest').click()
time.sleep(5)
def get_tweet_data(card):
find_username=card.find_element(by=By.XPATH, value='.//span').text
try:
find_twitter=card.find_element(by=By.XPATH, value='.//span[contains(text(), "#")]').text
except NoSuchElementException:
return
try:
find_date=card.find_element(by=By.XPATH, value='.//time').get_attribute('datetime')
except NoSuchelementException :
return
find_tweets1=card.find_element(by=By.XPATH, value='.//div[2]/div[2]/div[1]').text
find_tweets2=card.find_element(by=By.XPATH, value='.//div[2]/div[2]/div[2]').text
final_tweet=find_tweets1+find_tweets2
find_retweet=card.find_element(by=By.XPATH, value='.//div[#data-testid="retweet"]').text
find_reply=card.find_element(by=By.XPATH, value='.//div[#data-testid="reply"]').text
find_likes=card.find_element(by=By.XPATH, value='.//div[#data-testid="like').text
tweet=(find_username,find_twitter,find_date,final_tweet,find_retweet,find_reply,find_likes)
return tweet
data = []
tweet_ids = set()
last_position = driver.execute_script("return window.pageYOffset;")
scrolling = True
while scrolling:
page_cards = driver.find_elements(by=By.XPATH, value='//div[#data-testid="tweet"]')
for card in page_cards[-15:]:
tweet = get_tweet_data(card)
if tweet:
tweet_id = ''.join(tweet)
if tweet_id not in tweet_ids:
tweet_ids.add(tweet_id)
data.append(tweet)
scroll_attempt = 0
while True:
# check scroll position
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(5)
curr_position = driver.execute_script("return window.pageYOffset;")
if last_position == curr_position:
scroll_attempt += 1
# end of scroll region
if scroll_attempt >= 3:
scrolling = False
break
else:
time.sleep(5) # attempt another scroll
else:
last_position = curr_position
break
# close the web driver
driver.close()
with open('scrappeddata1.csv', 'w', newline='', encoding='utf-8') as f:
header = ['find_username','find_twitter','find_date','final_tweet','find_retweet','find_reply','find_likes']
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(data)
Please help to solve the issue
I am trying to automate login to the website https://research.axiscapital.co.in/.
I am able to add username and password. I have also automated solving the captcha. But after it solves the captcha, I am unable to click the login button. I get the WebDriverException: target frame detached exception. I am adding the code below (without the real username and password) for assistance.
NOTE: As soon as the captcha verification expires, the login button becomes clickable again. Kindly help me with it.
import requests
import time
import os
# Added for Selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
# TO MAKE THE SCRAPING FASTER
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://research.axiscapital.co.in/")
filename = '1.mp3'
delayTime = 2
googleIBMLink = 'https://speech-to-text-demo.ng.bluemix.net/'
audioToTextDelay = 10
def audioToText(mp3Path):
print("1")
driver.execute_script('''window.open("","_blank");''')
driver.switch_to.window(driver.window_handles[1])
print("2")
driver.get(googleIBMLink)
delayTime = 10
# Upload file
time.sleep(1)
print("3")
# Upload file
time.sleep(1)
root = driver.find_element_by_id('root').find_elements_by_class_name('dropzone _container _container_large')
btn = driver.find_element(By.XPATH, '//*[#id="root"]/div/input')
btn.send_keys('D:\\blogs\\1.mp3')
# Audio to text is processing
time.sleep(delayTime)
#btn.send_keys(path)
print("4")
# Audio to text is processing
time.sleep(audioToTextDelay)
print("5")
text = driver.find_element(By.XPATH, '//*[#id="root"]/div/div[7]/div/div/div').find_elements_by_tag_name('span')
print("5.1")
result = " ".join( [ each.text for each in text ] )
print("6")
driver.close()
driver.switch_to.window(driver.window_handles[0])
print("7")
return result
def saveFile(content,filename):
with open(filename, "wb") as handle:
for data in content.iter_content():
handle.write(data)
wait = WebDriverWait(driver,60)
wait.until(EC.element_to_be_clickable((By.XPATH, '//input[#id="Username"]'))).send_keys(username)
wait.until(EC.element_to_be_clickable((By.XPATH, '//input[#name="Password"]'))).send_keys(password)
time.sleep(1)
googleClass = driver.find_elements_by_class_name('g-recaptcha')[0]
time.sleep(2)
outeriframe = googleClass.find_element_by_tag_name('iframe')
time.sleep(1)
outeriframe.click()
time.sleep(2)
allIframesLen = driver.find_elements_by_tag_name('iframe')
time.sleep(1)
audioBtnFound = False
audioBtnIndex = -1
for index in range(len(allIframesLen)):
driver.switch_to.default_content()
iframe = driver.find_elements_by_tag_name('iframe')[index]
driver.switch_to.frame(iframe)
driver.implicitly_wait(delayTime)
try:
audioBtn = driver.find_element_by_id('recaptcha-audio-button') or driver.find_element_by_id('recaptcha-anchor')
audioBtn.click()
audioBtnFound = True
audioBtnIndex = index
break
except Exception as e:
pass
if audioBtnFound:
try:
while True:
href = driver.find_element_by_id('audio-source').get_attribute('src')
response = requests.get(href, stream=True)
saveFile(response,filename)
response = audioToText(os.getcwd() + '/' + filename)
print(response)
driver.switch_to.default_content()
iframe = driver.find_elements_by_tag_name('iframe')[audioBtnIndex]
driver.switch_to.frame(iframe)
inputbtn = driver.find_element_by_id('audio-response')
inputbtn.send_keys(response)
inputbtn.send_keys(Keys.ENTER)
time.sleep(2)
errorMsg = driver.find_elements_by_class_name('rc-audiochallenge-error-message')[0]
if errorMsg.text == "" or errorMsg.value_of_css_property('display') == 'none':
print("Success")
break
except Exception as e:
print(e)
print('Caught. Need to change proxy now')
else:
print('Button not found. This should not happen.')
time.sleep(4)
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Login"]'))).click()
You forgot to switch to default context after successfully completing the captcha.
put driver.switch_to.default_content() before break.
Edit: the success block would look like this.
print("Success")
driver.switch_to.default_content()
break
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()
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")