Manas Dogra
Manas Dogra

Reputation: 317

How to obtain received message from "facebook messages" page using selenium?

I am trying to write a Python program which will fetch the last message from a person from facebook messages page(similar to facebook messenger) as soon as he texts and print it in a Python IDE.

I am using Selenium to open the page and get to the textbox of the person from whom I am expecting the message.I have no idea how to proceed from there because everytime the new text comes the xpath,selector etc of the new text changes and even if I use expected_conditions, on what should I? The element itself is changing.If I could get the element id or xpath or otherwise, I could easily use gettext() methods to obtain the text.

Below is my minimal code, for reaching upto the textbox of the guy from whom I am expecting messages-

from selenium import webdriver 

usr = "x******@gmail.com" 
pwd = "y*****"

opt = webdriver.ChromeOptions()
opt.add_experimental_option("prefs",{"profile.default_content_setting_values.notifications":2}) # Block_notifications
driver = webdriver.Chrome('C:\Chromedriver\chromedriver.exe',chrome_options=opt)

driver.get('https://www.facebook.com/') 
username_box = driver.find_element_by_id('email') 
username_box.send_keys(usr) 
password_box = driver.find_element_by_id('pass') 
password_box.send_keys(pwd) 
login_box = driver.find_element_by_id('u_0_b') 
login_box.click()
driver.get("https://www.facebook.com/messages/t/userid") 
textbox = driver.find_element_by_xpath(r"""//*[@id="js_i"]/div/div/div""")

How to proceed from here, to get the message when he does?

Upvotes: 0

Views: 1126

Answers (1)

Dilip Meghwal
Dilip Meghwal

Reputation: 632

Your problem will be solved by follwing below steps.

  1. Switch to frame driver.switch_to_frame("//iframe[contains(@src,'userid')]") (Note : Here 'userid' is chat username.)
  2. Use this XPath //div[@data-hover='tooltip']/div[@role='img'] to identify the facebook smilies or GIF images.
  3. Use this XPath //div[@data-hover='tooltip']/div/span to read the chat text.

Upvotes: 1

Related Questions