Skip to main content
 首页 » 编程设计

python之使用 Python 和 Selenium 向 Facebook 中的 friend 发送消息

2025年01月19日11powertoolsteam

我目前正在用 Python 编写一个脚本来登录 facebook,我想向 friend 发送消息。该脚本登录到我的 facebook,它设法找到了我的 friend ,但没有发送消息。我不是 100% 确定,但我认为问题出在文本区域的 div 标记/CSS 中(我注释掉了那段代码)。

截图: Text doesn't appear here

这是我的代码:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
 
driver = webdriver.Chrome('C:\path\chromedriver.exe') 
driver.get('https://www.facebook.com/') 
 
username_box = driver.find_element_by_id('email') 
username_box.send_keys(USEREMAIL) 
passElem = driver.find_element_by_id("pass") 
passElem.send_keys(USERPASSWORD) 
passElem.send_keys(Keys.RETURN) 
userTargetUrl = "https://www.facebook.com/messages/t/" + "USERTAGET" 
driver.get(userTargetUrl) 
 
//The problem is here I think 
    elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize") 
 
 
    while True: 
        elem.send_keys("Test") 
        elem.send_keys(Keys.RETURN) 
        driver.find_element_by_id("u_0_t").click() 

我得到的错误代码是:

selenium.common.exceptions.NoSuchElementException:  
Message: no such element: Unable to locate element:  
{"method":"css selector","selector":"div textarea.uiTextareaNoResize"} 
  (Session info: chrome=63.0.3239.132) 
  (Driver info: chromedriver=2.35.528161  
(5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.15063 x86_64) 

请您参考如下方法:

我在 RU SO 上解决了这个问题)))

简要步骤:

  1. 导入库

    从 selenium.webdriver.common.action_chains 导入 ActionChains

  2. 访问了网站

  3. 登录

  4. 您有一个 friend 列表,您点击了 friend 的图标并打开了一个聊天窗口。

现在该怎么办?))

  1. You need to place the cursor in the input line, in which is not write the text) 为此.click()使用,你可以使用任何你的XPath,但是这里是一个较短的))

    driver.find_element_by_xpath("//*[@data-editor]").click()

  2. 按下.click()方法后,光标放在文本输入区。现在我们需要输入文本,但是使用 .send_keys() 不是像您尝试的那样使用指向元素的指针,而是单独作为一个 Action (这就是导入库的用途) Action = ActionChains(驱动程序) actions.send_keys('HI') actions.perform()

呜啦啦))))

好吧,在发送图标上 .click() 或按 Enter)))))