我最近在使用 python 中的 selenium 模块时遇到了很多麻烦。我正在尝试制作一个脚本,可以根据其中一位朋友的要求自动向我的朋友发送消息。
我可以用它登录 Google Hangouts,但是我在访问聊天时遇到了相当大的困难。如果我想点击一个对话来打开聊天窗口,我想我可以用 selenium 的 find_element_by_id() 函数来选择 id。
但是,这不起作用,因为环聊使用在某些事件后会更改的动态 ID。我真的不知道该怎么办。我尝试使用 xpath,但这也不起作用。我真的不知道此时该做什么,因为我正在尝试的任何事情似乎都不起作用。
如果您想自己重现此内容,则必须获取 chromedriver 并输入路径。您还必须将自己的电子邮件和密码输入到正确的 send_keys() 函数中。
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:
温温酱
相关分类