我使用我撰寫的代碼在 WhatsApp 上向多個聯系人發送訊息,但在發送所有訊息之前,Chrome 已關閉,并且某些訊息未發送。如何確定我發送的訊息已發送?(這不是程式的問題) 問題是網速慢,要等一會才能發訊息
from bs4 import BeautifulSoup
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import os
class WhatsApp:
def __init__(self) -> None:
user = os.getlogin()
options = webdriver.ChromeOptions()
# options.headless = True
options.add_argument('--profile-directory=Default')
options.add_argument(
f'--user-data-dir=C:\\Users\\{user}\\AppData\\Local\\Google\\Chrome\\User Data')
PATH = "chromedriver_win32\chromedriver.exe"
self.driver = webdriver.Chrome(
executable_path=PATH, chrome_options=options)
self.driver.set_window_position(0, 0)
self.driver.set_window_size(0, 0)
self.driver.get("https://web.whatsapp.com")
WebDriverWait(self.driver, 5000).until(
EC.presence_of_element_located(
(By.XPATH, '//*[@id="side"]/header/div[2]/div/span/div[2]/div'))
)
def send_msg(self, phone: str, msg: str):
search_btn = self.driver.find_element_by_xpath(
'//*[@id="side"]/header/div[2]/div/span/div[2]/div')
search_btn.send_keys(Keys.ENTER)
input_search = self.driver.find_element_by_xpath(
'/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[1]/div/label/div/div[2]')
input_search.send_keys(phone, Keys.ENTER)
try:
sleep(1)
self.driver.find_element_by_xpath(
"/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]").send_keys(
msg, Keys.ENTER)
except Exception as e:
pass
# showMessageBox.contacte_not_found(showMessageBox)
def check_is_sended(self, phone: str, msg: str):
pass
#some code i need to check message sended or not
def END(self):
sleep(3)
self.driver.close()
app = WhatsApp()
phone = " 98xxxxxxxx87"
message = "test"
app.send_msg(phone , message)
app.END()
所以我不想長時間使用睡眠我只是想找到最好的方法來縮短運行程式的時間任何 id?
uj5u.com熱心網友回復:
當 selenium 單擊“發送訊息按鈕”時,
將在 html 中創建一個新的 div,指示您發送了一條訊息。所以,讓 selenium 等到它出現。

然后使 selenium 也等待
指示 msg 已成功發送到 Whatsapp 服務器的驗證圖示。
問:我如何獲得新訊息?A:你可以等到聊天室的html-div包含你發送的msg。
from selenium.webdriver.support import expected_conditions as EC
locator = (By.ID, 'someid') #modify this according to your case
your_new_msg = 'blabla bla' #modify this according to your case
wait.until(EC.text_to_be_present_in_element(locator, your_new_msg))
但是這個簡短的解決方案可能會導致錯誤,因為該訊息可能存在于聊天室 div 中的另一個舊訊息中。所以,selenium 會認為它是預期的 msg 然后錯誤地退出等待。
因此,如果您是新開發人員,則此問題的解決方案可能對您來說很難。
您需要在 Python 和 Javascript 之間建立一個通道以在它們之間傳遞資料,
然后在 JS 中創建一個事件偵聽器來觀察聊天室的變化(例如:您可以覆寫 (chat-room-div).appendChild 方法。然后你在 JS 方法中獲得了 new-msg html 元素,然后它才顯示在 html 上)
然后你可以從 JS 發送一個 msg 到 python 告訴他 new-msg div 已經出現并且驗證圖示也出現了
然后python將退出它的等待狀態。然后繼續執行下一個代碼_____這只是想法。它的實施取決于你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/463174.html
標籤:python-3.x 硒 美丽的汤 whatsapp
