1

I am using the Webbrowser library in python to sent messages on WhatsApp. But the problem is that I have to click on send message manually by going to whatsapp and clicking send.

This is my code:

import webbrowser


num = ('72********')

message = ("Message sent using python!!!")

a = webbrowser.open(f'https://web.whatsapp.com/send?phone=+46{name}&text={message}', new = 2)

print('waiting..')

The code is working fine but, I was wondering how you can send the message without manually clicking send?

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
Harsimrat
  • 11
  • 3

1 Answers1

0

For this task I would recommend a library that is suited to the task, such as selenium (installation guide).

With that you can do:

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# settings
num = '+## ###########'
message = "Hello World!"
username = 'Robson'

# create an instance of chrome, which uses/remembers settings
options = Options()
options.add_argument("user-data-dir=C:\\Users\\" + username + "\\AppData\\Local\\Google\\Chrome\\User Data")
driver = webdriver.Chrome(options=options)

# go to our specific whatsapp web url
driver.get(f'https://web.whatsapp.com/send?phone={num}&text={message}');

# wait for the page to fully load
# there are better ways to do this, but I don't want to over-complicate this solution
time.sleep(5);

# find the send button and click it
driver.find_element_by_xpath("//span[@data-icon='send']/..").click()

That opens an automated instance of Chrome, navigates to WhatsApp Web and then sends a message after five seconds to the intended recipient.

Make sure to change the settings before running this. The username is your Windows username.

You'll need to log-in to WhatsApp Web manually the first time, but after that it will log you in automatically.

I'm away for a while, but please do ask any questions in the comments and I'll reply when I'm back.

Robson
  • 2,008
  • 2
  • 7
  • 26