def post_comment(driver, comment):
try:
# Wait for the comment button and click it
comment_button = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//span[contains(text(), 'Comment')]"))
)
comment_button.click()
time.sleep(3) # Wait for the comment box to appear
# Wait for the comment box to appear and click it
comment_box = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//div[@role='textbox' and @aria-label='Write a comment...']"))
)
comment_box.click() # Click to focus on the comment box
comment_box.send_keys(comment) # Type the comment
# Retry sending the comment if necessary
max_attempts = 5
for attempt in range(max_attempts):
try:
# Wait for the send button using the provided XPath
send_button = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//div[@aria-label='Send']"))
)
send_button.click() # Click the send button
print(f"Posted comment: {comment}")
return # Exit the function if successful
except Exception as e:
print(f"Attempt {attempt + 1}: Failed to click send button. Retrying...")
time.sleep(2) # Wait before retrying
print("Max attempts reached. Failed to post comment.")
except Exception as e:
print(f"Failed to post comment: {e}")