使用Python操作Whatsapp?


在本節中,我們將建立一個Whatsapp聊天機器人,但與其他一些針對Twitter或Facebook的聊天機器人不同,由於Whatsapp的政策,Whatsapp聊天機器人不會直接在平臺上執行。

但是,有一種方法可以實現它,那就是使用Selenium,這是一個非常智慧的Python包,開發人員可以使用它來自動化瀏覽器的活動。透過這種方式,我們可以透過瀏覽器使用Whatsapp網頁版。

需求

我們需要三樣基本的東西來完成任務:Selenium。

我們可以使用pip非常輕鬆地安裝Selenium,只需在您的終端執行以下命令:

$pip install selenium

以下是一個簡單的程式,用於使用Python向特定聯絡人傳送Whatsapp訊息。

示例

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
import sys
# Replace below path with the absolute path of the \
#chromedriver in your computer
driver = webdriver.Chrome(r'c:\users\rajesh\Desktop\chromedriver')

driver.get("https://web.whatsapp.com/")
# time.sleep()
wait = WebDriverWait(driver, 600)
# Replace 'My Bsnl' with the name of your friend or group name
target = '"My Bsnl"'

# Replace the below string with your own message
string = sys.argv[1]

x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located((
By.XPATH, x_arg)))
print (group_title)
print ("Wait for few seconds")
group_title.click()
message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]

message.send_keys(string)
sendbutton = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[3]/button')[0]
sendbutton.click()
driver.close()

讓我們在命令提示符下執行上述指令碼,將訊息作為引數傳遞給Whatsapp聯絡人:

>python whatsppPython.py "Hello"

DevTools listening on ws://127.0.0.1:12954/devtools/browser/a5bb04bd-66a3-4002-999f-6a0824f591da
<selenium.webdriver.remote.webelement.WebElement (session="83e7034b9a6f6b49e9e422e655f270d3", element="0.30994636046479007-1")>
after wait
….
…..

Chrome瀏覽器將開啟,螢幕上會顯示類似以下內容:

在您的移動裝置上,從Whatsapp頂部的工具欄中選擇Whatsapp網頁版。掃描螢幕上顯示的二維碼。

在那裡我們可以看到訊息已傳送到我們案例中的特定聯絡人(“我的Bsnl”)。

更新於:2019年7月30日

604 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告