You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium实现Facebook Messenger发消息遇动态xpath定位问题求解

Facebook Messenger Selenium自动发消息定位问题解决方案

核心问题说明

  • 你使用的绝对XPath、mount_0_0_开头的随机id都是Facebook前端动态渲染的属性,每次刷新页面都会重新生成,无法用于稳定定位。
  • find_element_by_class_name方法不支持传入多个带空格的类名,你写的一长串类名会直接触发定位错误。
  • 硬编码的time.sleep等待效率低,很容易出现元素未加载完成就执行定位的问题。

修正方案

定位逻辑优化

  • 消息输入框:使用相对XPath结合稳定属性定位,Messenger的输入框默认带有contenteditable="true"全局属性,也可以用CSS选择器替换类名定位(多个类名用.连接)。
  • 发送按钮:放弃带随机前缀的绝对路径,用相对XPath匹配表单下的按钮元素即可,稳定性更高。
  • 替换硬等待为Selenium显式等待,自动检测元素加载状态,提升代码容错率。
  • 修正新版本Selenium的弃用参数写法,chrome_options参数已废弃,统一改为options。

修正后代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

i = 1
text = input("enter the text messege")
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=chrome_options)
driver.get(r"https://www.facebook.com/messages/t/2585929161530825/")

wait = WebDriverWait(driver, 15)
# 登录流程改用显式等待
email_box = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="email"]')))
email_box.click()
email_box.send_keys("xnxx@gmail.com")

password_box = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="pass"]')))
password_box.click()
password_box.send_keys("rockyou.txt")

login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="loginbutton"]')))
login_button.click()

# 等待登录跳转完成
time.sleep(10)

while i != 3000:
     # CSS选择器匹配多类名定位输入框
     chat_box = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.ecm0bbzt.e5nlhep0.buofh1pr.jq4qci2q.a3bd9o3v')))
     # 也可以用更稳定的属性定位:(By.XPATH, '//div[@contenteditable="true"]')
     chat_box.click()
     chat_box.send_keys(text, "{}".format(i))
     # 相对路径定位发送按钮
     send_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//form//div[@role="button"]//svg')))
     send_button.click()
     if i == 5:
          time.sleep(2)
     i += 1

如果上述定位规则失效,可以打开F12元素选择器,选中输入框后筛选不会变化的属性拼接组合定位规则,比如//div[@aria-label="消息" and @contenteditable="true"],定位稳定性远高于自动生成的绝对路径。

内容的提问来源于stack exchange,提问作者biplab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 11:15:01