from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # Add for keyboard actions
import time
# Function to read contacts from the file
def read_contacts_from_file(file_path):
with open(file_path, 'r') as file:
return [line.strip() for line in file.readlines()] # Return a list of contact numbers
# Function to read message from a file
def read_message_from_file(file_path):
with open(file_path, 'r') as file:
return file.read().strip() # Return the message text, removing any surrounding whitespace
# Configure Firefox options
options = webdriver.FirefoxOptions()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' # Path to Firefox
options.set_preference("profile", "C:/Users/Aman/AppData/Roaming/Mozilla/Firefox/Profiles/your_profile_name")
# Initialize the WebDriver for Firefox
gecko_driver_path = r'C:\Users\97338\Downloads\geckodriver-v0.35.0-win32\geckodriver.exe'
service = webdriver.firefox.service.Service(gecko_driver_path)
driver = webdriver.Firefox(service=service, options=options)
# Open WhatsApp Web
driver.get("https://web.whatsapp.com/")
time.sleep(5) # Give time for WhatsApp Web to load
wait = 120
# Read the contact numbers from the file
contact_number_file_path = r"C:\Users\97338\Downloads\contact_number.txt"
contacts = read_contacts_from_file(contact_number_file_path)
video_path = r"C:\Users\97338\Downloads\test_video.mp4"
# Read the message from the file
message_file_path = r"C:\Users\97338\Downloads\massage.txt"
message = read_message_from_file(message_file_path)
print(f"Message read from file: {message}")
# List to keep track of already sent contacts
sent_contacts = []
# Select the chat container for scrolling
chat_container_xpath = '//*[@id="pane-side"]' # This is the chat list container
for target in contacts:
if target in sent_contacts:
print(f"Skipping '{target}' because it has already been sent the video.")
continue # Skip the contact if it's already in the sent list
try:
# Print "Locating contact..." before trying to locate the contact
print(f"Locating contact '{target}'...")
contact_path = f'//span[contains(@title,"{target}")]'
# Start a timer to limit the contact search to 20 seconds
start_time = time.time()
contact_found = False
# First attempt: search without scrolling for 20 seconds
while time.time() - start_time < 20:
try:
contact = driver.find_element(By.XPATH, contact_path) # Directly find the element
contact_found = True
print(f"Found contact '{target}' immediately.")
break # Exit if contact is found
except:
pass # Continue searching until the 20 seconds are up
# If the contact is not found in the first 20 seconds, start scrolling
if not contact_found:
print(f"Contact '{target}' not found after initial 20 seconds. Starting to scroll...")
scroll_start_time = time.time()
scroll_count = 0
previous_scroll_position = None # To track when we've reached the end of the list
# Scroll 40 times or until the contact is found
while scroll_count < 40:
print(f"Scrolling... attempt {scroll_count + 1}")
chat_container = driver.find_element(By.XPATH, chat_container_xpath)
driver.execute_script("arguments[0].scrollTop += 200;", chat_container) # Scroll incrementally by 200px
time.sleep(1) # Wait for 1 second to load the new content
scroll_count += 1
# Check the page scroll and print the scroll position for debugging
scroll_position = driver.execute_script("return arguments[0].scrollTop;", chat_container)
print(f"Current scroll position: {scroll_position}")
try:
# Check for the contact again after scrolling
contact = driver.find_element(By.XPATH, contact_path)
contact_found = True
print(f"Found contact '{target}' after scrolling.")
break # Exit if contact is found
except:
pass # Keep scrolling if the contact is not found yet
# If we've reached the bottom (scrolling stops) and no contact found, stop scrolling
if scroll_position == previous_scroll_position:
print("Reached the bottom of the chat list. Stopping scroll.")
break
previous_scroll_position = scroll_position
if not contact_found:
print(f"Contact '{target}' not found after scrolling for 40 attempts.")
continue # Skip to the next contact if not found
# Scroll into view before clicking
driver.execute_script("arguments[0].scrollIntoView(true);", contact)
# Ensure the contact is clickable and click it
contact.click()
print(f"Contact '{target}' clicked")
# Locate the Attach button
attach_button_path = '//button[@aria-label="Attach" and @data-tab="10"]'
attach_button = driver.find_element(By.XPATH, attach_button_path)
attach_button.click()
print("Attach button clicked")
# Locate the "Photos & Videos" button
photos_videos_button_path = '//li[contains(., "Photos & videos")]'
photos_videos_button = driver.find_element(By.XPATH, photos_videos_button_path)
photos_videos_button.click()
print("Photos & Videos button clicked")
# Wait for the file input element to appear
file_input_path = '//input[@type="file"]'
file_input = driver.find_element(By.XPATH, file_input_path)
# Upload the video file
file_input.send_keys(video_path)
print(f"Video {video_path} uploaded")
# Wait for the message box to appear and add the message
time.sleep(1) # Wait for a moment to ensure the message box is ready
# Locate the message input box using its XPath (based on the provided HTML)
message_box_xpath = '//div[@contenteditable="true"]' # Using the provided HTML class
message_box = driver.find_element(By.XPATH, message_box_xpath)
# Focus on the message box to ensure it is active
driver.execute_script("arguments[0].focus();", message_box)
# Clear any default or previous text in the box
message_box.clear()
# Send the message read from the file
message_box.send_keys(message)
print(f"Message '{message}' added to the message box.")
# Wait briefly before sending the video with the message
time.sleep(2)
# Locate the Send button and click it using JavaScript to bypass any click interception
send_button_path = '//span[@data-icon="send"]'
send_button = driver.find_element(By.XPATH, send_button_path)
driver.execute_script("arguments[0].click();", send_button) # JavaScript click
print(f"Video with message sent to '{target}'")
# Wait to confirm the message is sent
time.sleep(3)
# Check if the message was sent successfully by looking for the new message XPath
try:
# Check for the new span element indicating message was sent
sent_message_xpath = '//span[@class="selectable-text copyable-text false"][@data-lexical-text="true"]'
sent_message = driver.find_element(By.XPATH, sent_message_xpath)
print(f"Message successfully sent to '{target}'")
except:
print(f"Message was not sent to '{target}'. Retrying...")
message_box = driver.find_element(By.XPATH, message_box_xpath)
message_box.clear() # Clear previous text
message_box.send_keys(message) # Retry sending the message
driver.execute_script("arguments[0].click();", send_button) # Retry click to send
print(f"Retrying to send message to '{target}'")
# Add this contact to the sent list
sent_contacts.append(target)
print(f"'{target}' has been added to the sent contacts list.")
# Scroll all the way up after the scroll is done
chat_container = driver.find_element(By.XPATH, chat_container_xpath) # Ensure the chat_container is defined before using
driver.execute_script("arguments[0].scrollTop = 0;", chat_container) # Scroll to the top
print("Scrolled all the way to the top.")
except Exception as e:
print(f"Error sending to '{target}': {e}")
# Pause before processing
пробовал изменить xpath и сначала набрать сообщение, но все равно что-то произошло, также пытался дать больше времени для ввода и проверки правильности текста, но при этом также была напечатана только первая буква< /п>
Этот код должен отправлять сообщение с видео, но когда я пробую его, видео отправляется, но отправляется только первая буква сообщения [code] from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys # Add for keyboard actions import time
# Function to read contacts from the file def read_contacts_from_file(file_path): with open(file_path, 'r') as file: return [line.strip() for line in file.readlines()] # Return a list of contact numbers
# Function to read message from a file def read_message_from_file(file_path): with open(file_path, 'r') as file: return file.read().strip() # Return the message text, removing any surrounding whitespace
# Initialize the WebDriver for Firefox gecko_driver_path = r'C:\Users\97338\Downloads\geckodriver-v0.35.0-win32\geckodriver.exe' service = webdriver.firefox.service.Service(gecko_driver_path) driver = webdriver.Firefox(service=service, options=options)
# Open WhatsApp Web driver.get("https://web.whatsapp.com/") time.sleep(5) # Give time for WhatsApp Web to load wait = 120
# Read the contact numbers from the file contact_number_file_path = r"C:\Users\97338\Downloads\contact_number.txt" contacts = read_contacts_from_file(contact_number_file_path) video_path = r"C:\Users\97338\Downloads\test_video.mp4"
# Read the message from the file message_file_path = r"C:\Users\97338\Downloads\massage.txt" message = read_message_from_file(message_file_path) print(f"Message read from file: {message}")
# List to keep track of already sent contacts sent_contacts = []
# Select the chat container for scrolling chat_container_xpath = '//*[@id="pane-side"]' # This is the chat list container
for target in contacts: if target in sent_contacts: print(f"Skipping '{target}' because it has already been sent the video.") continue # Skip the contact if it's already in the sent list
try: # Print "Locating contact..." before trying to locate the contact print(f"Locating contact '{target}'...")
# Start a timer to limit the contact search to 20 seconds start_time = time.time() contact_found = False
# First attempt: search without scrolling for 20 seconds while time.time() - start_time < 20: try: contact = driver.find_element(By.XPATH, contact_path) # Directly find the element contact_found = True print(f"Found contact '{target}' immediately.") break # Exit if contact is found except: pass # Continue searching until the 20 seconds are up
# If the contact is not found in the first 20 seconds, start scrolling if not contact_found: print(f"Contact '{target}' not found after initial 20 seconds. Starting to scroll...")
scroll_start_time = time.time() scroll_count = 0 previous_scroll_position = None # To track when we've reached the end of the list
# Scroll 40 times or until the contact is found while scroll_count < 40: print(f"Scrolling... attempt {scroll_count + 1}") chat_container = driver.find_element(By.XPATH, chat_container_xpath) driver.execute_script("arguments[0].scrollTop += 200;", chat_container) # Scroll incrementally by 200px time.sleep(1) # Wait for 1 second to load the new content scroll_count += 1
# Check the page scroll and print the scroll position for debugging scroll_position = driver.execute_script("return arguments[0].scrollTop;", chat_container) print(f"Current scroll position: {scroll_position}")
try: # Check for the contact again after scrolling contact = driver.find_element(By.XPATH, contact_path) contact_found = True print(f"Found contact '{target}' after scrolling.") break # Exit if contact is found except: pass # Keep scrolling if the contact is not found yet
# If we've reached the bottom (scrolling stops) and no contact found, stop scrolling if scroll_position == previous_scroll_position: print("Reached the bottom of the chat list. Stopping scroll.") break
previous_scroll_position = scroll_position
if not contact_found: print(f"Contact '{target}' not found after scrolling for 40 attempts.") continue # Skip to the next contact if not found
# Scroll into view before clicking driver.execute_script("arguments[0].scrollIntoView(true);", contact)
# Ensure the contact is clickable and click it contact.click() print(f"Contact '{target}' clicked")
# Locate the Attach button attach_button_path = '//button[@aria-label="Attach" and @data-tab="10"]' attach_button = driver.find_element(By.XPATH, attach_button_path) attach_button.click() print("Attach button clicked")
# Wait for the file input element to appear file_input_path = '//input[@type="file"]' file_input = driver.find_element(By.XPATH, file_input_path)
# Upload the video file file_input.send_keys(video_path) print(f"Video {video_path} uploaded")
# Wait for the message box to appear and add the message time.sleep(1) # Wait for a moment to ensure the message box is ready
# Locate the message input box using its XPath (based on the provided HTML) message_box_xpath = '//div[@contenteditable="true"]' # Using the provided HTML class message_box = driver.find_element(By.XPATH, message_box_xpath)
# Focus on the message box to ensure it is active driver.execute_script("arguments[0].focus();", message_box)
# Clear any default or previous text in the box message_box.clear()
# Send the message read from the file message_box.send_keys(message) print(f"Message '{message}' added to the message box.")
# Wait briefly before sending the video with the message time.sleep(2)
# Locate the Send button and click it using JavaScript to bypass any click interception send_button_path = '//span[@data-icon="send"]' send_button = driver.find_element(By.XPATH, send_button_path) driver.execute_script("arguments[0].click();", send_button) # JavaScript click print(f"Video with message sent to '{target}'")
# Wait to confirm the message is sent time.sleep(3)
# Check if the message was sent successfully by looking for the new message XPath try: # Check for the new span element indicating message was sent sent_message_xpath = '//span[@class="selectable-text copyable-text false"][@data-lexical-text="true"]' sent_message = driver.find_element(By.XPATH, sent_message_xpath) print(f"Message successfully sent to '{target}'") except: print(f"Message was not sent to '{target}'. Retrying...") message_box = driver.find_element(By.XPATH, message_box_xpath) message_box.clear() # Clear previous text message_box.send_keys(message) # Retry sending the message driver.execute_script("arguments[0].click();", send_button) # Retry click to send print(f"Retrying to send message to '{target}'")
# Add this contact to the sent list sent_contacts.append(target) print(f"'{target}' has been added to the sent contacts list.")
# Scroll all the way up after the scroll is done chat_container = driver.find_element(By.XPATH, chat_container_xpath) # Ensure the chat_container is defined before using driver.execute_script("arguments[0].scrollTop = 0;", chat_container) # Scroll to the top print("Scrolled all the way to the top.")
except Exception as e: print(f"Error sending to '{target}': {e}")
# Pause before processing [/code] пробовал изменить xpath и сначала набрать сообщение, но все равно что-то произошло, также пытался дать больше времени для ввода и проверки правильности текста, но при этом также была напечатана только первая буква< /п>