簡體   English   中英

使用 Python 和 Selenium 向 Facebook 中的朋友發送消息

[英]Using Python & Selenium to send message to friend in Facebook

我目前正在用 Python 編寫一個腳本來登錄 facebook,我想向朋友發送消息。 該腳本登錄到我的 facebook,它設法找到了我的朋友,但沒有發送消息。 我不是 100% 確定,但我認為問題出在文本區域上的 div 標簽/CSS(我注釋掉了那段代碼)。

屏幕截圖:此處未顯示文本

這是我的代碼:

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. 進行庫導入

    from selenium.webdriver.common.action_chains import ActionChains

  2. 訪問了網站

  3. 已登錄

  4. 您有一個朋友列表,您單擊了朋友的圖標並打開了一個聊天窗口。

現在該怎么辦?))

  1. 您需要將光標放在輸入行中,其中未寫入文本)為此使用.click () ,您可以使用任何您的 XPath,但這里是一個較短的))

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

  2. 按下.click ()方法后,光標放置在文本輸入區。 現在我們需要輸入文本,但是使用.send_keys()不是像您嘗試的那樣與指向元素的指針一起使用,而是單獨作為一個動作(這是導入的庫的用途) actions = ActionChains(driver) actions.send_keys('HI') actions.perform()

哇啦))))

在此處輸入圖片說明

好吧,之后.click()在發送圖標上或按 Enter)))))

嘗試按名稱、id、文本或任何其他唯一參數查找元素 - 會更好(它們有時會更改設計並且所有 xpath 和 css 選擇器都變得無用)。

我大膽地使用了:

 <div aria-autocomplete="list" aria-controls="js_7" aria-describedby="js_0" aria-expanded="false" <b>aria-label="Введите сообщение..."</b> class="notranslate _5rpu" role="combobox" spellcheck="true" style="outline: medium none currentcolor; -moz-user-select: text; white-space: pre-wrap; overflow-wrap: break-word;" <b>tabindex="9999"<b> <b>id="js_d"</b> contenteditable="true"><div data-contents="true">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM