I've been having a lot of trouble with the selenium module in python recently. I am trying to make a script that can automate sending messages to my friends as requested by one of them.
I am able to log into Google Hangouts with it, but I am having considerable difficulty in accessing the chats. If I want to click on a conversation to open the chat window, I would think that I could just select the id with selenium's find_element_by_id() function.
However, this does not work as Hangouts uses dynamic ids which change after certain events. I don't really know what to do. I tried using the xpath but that doesn't work either. I don't really know what do at this point as nothing I'm trying seems to work.
If you want to reproduce this for yourself, you are going to have to get chromedriver and input the path. You are also going to have to put in your own email and password into the the correct send_keys() functions.
from selenium import webdriver
import time
# get browser set up
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
browser = webdriver.Chrome(options=options,
executable_path=r"chromedriver path")
browser.get('https://stackoverflow.com/users/login')
# locate and click sign in button on stackoverflow (can't sign in on regular google)
google_button = browser.find_element_by_class_name('s-btn__google')
google_button.click()
email_elem = browser.find_element_by_id('identifierId')
email_elem.send_keys('email')
next_button = browser.find_element_by_id('identifierNext')
next_button.click()
# enters password
while True:
try:
pwd_elem = browser.find_element_by_css_selector('input[type = "password"]')
pwd_elem.send_keys('password')
break
except:
time.sleep(1)
next_button = browser.find_element_by_id("passwordNext")
next_button.click()
while True:
try:
# gets to hangouts
browser.execute_script('''window.open("https://hangouts.google.com/", "_blank");''')
browser.switch_to.window(browser.window_handles[-1])
break
except:
time.sleep(1)
refreshed = False
while True:
try:
# CAN'T FIND PATH TO CHAT
chat = browser.find_element_by_xpath('/html/body/div/div/div/div/div[2]/div/div/div[2]/div/div/div/div/div[1]/div[1]/div/div[1]')
chat.click()
break
except:
print('not found')
if not refreshed:
# refreshes because hangouts will first load without signing in
browser.refresh()
refreshed = True
time.sleep(4)