无法使用Python发送WhatApp消息

时间:2019-08-21 00:21:25

标签: python whatsapp

我正在使用下面的代码示例。我从https://www.geeksforgeeks.org/whatsapp-using-python/

获得

我对代码进行了必要的更改。例如“与实际的朋友更改'朋友的名字'”,“下载chromedriver”等。

运行代码后,我注意到它堆积在input_box=wait.until(EC.presence_of_element_located((By.XPATH, inp_xpath)))行。

stack-> mean:代码正在等待直到超时,然后给出与超时问题相关的错误

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 

# Replace below path with the absolute path 
# to chromedriver in your computer 
driver = webdriver.Chrome('/home/saket/Downloads/chromedriver') 

driver.get("https://web.whatsapp.com/") 
wait = WebDriverWait(driver, 600) 

# Replace 'Friend's Name' with the name of your friend 
# or the name of a group 
target = '"Friend\'s Name"'

# Replace the below string with your own message 
string = "Message sent using Python!!!"

x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located(( 
    By.XPATH, x_arg))) 
group_title.click() 
inp_xpath = '//div[@class="input"][@dir="auto"][@data-tab="1"]'
input_box = wait.until(EC.presence_of_element_located(( 
    By.XPATH, inp_xpath))) 
for i in range(100): 
    input_box.send_keys(string + Keys.ENTER) 
    time.sleep(1) 

我希望将“字符串”消息发送到“目标”。有什么可以帮助我解决我的问题的吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

sally-zeitler发表评论之后,我尝试了一些事情。

  1. 由于inp_xpath变量在我的Chrome浏览器中不同,因此我将其更改为正确的变量。
  2. Chrome浏览器和chromedriver存在兼容性问题,因此我已下载了正确的兼容问题(如果您使用的是Chrome版本76,请下载ChromeDriver 76.0.3809.126)
  3. 然后,它很好用:)

这是代码示例的最新版本:

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

# Replace below path with the absolute path
# to chromedriver in your computer
driver = webdriver.Chrome('/home/saket/Downloads/chromedriver')

driver.get("https://web.whatsapp.com/")
wait = WebDriverWait(driver, 500)
print("#1")
# Replace 'Friend's Name' with the name of your friend
# or the name of a group
#target = '"Friend\'s Name"'
target = '"Your friend name"'
print("#2")
# Replace the below string with your own message
string = '"Message sent using Python!!!"'
print("#3")
x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located((
    By.XPATH, x_arg)))
print("#4")
group_title.click()
print("#5")
inp_xpath = '//div[@class="_3u328 copyable-text selectable-text"]'
input_box = wait.until(EC.presence_of_element_located((
    By.XPATH, inp_xpath)))
print("#6")
for i in range(100):
    print("#7", i)
    input_box.send_keys(string + Keys.ENTER)
    time.sleep(1)