首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用selenium、python和whatsapp-web等待元素显示而不显示。

使用selenium、python和whatsapp-web等待元素显示而不显示。
EN

Stack Overflow用户
提问于 2019-01-18 00:23:39
回答 2查看 1.4K关注 0票数 2

我试图使用" whatsapp -web“、"selenium”和"python 3“来了解whatsapp用户何时上线或离线。

为了解释更多,我希望脚本工作如下:

脚本将侦听要显示的span (带有title=online),当span显示时(这意味着用户在线),我希望此时打印时间,然后脚本将继续侦听以使span消失,当脚本消失时,脚本打印消失的时间,等等。

这是我的密码:

代码语言:javascript
运行
复制
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import datetime

driver = webdriver.Chrome('C:/webdrivers/chromedriver.exe')
driver.get('https://web.whatsapp.com/')

# do nothing until QR code scanned and whatsapp-web is accessed
input('Enter anything after scanning QR code')

# Input the name of the user to track
name = input('Enter the name of the user : ')

# find the whatsapp user to be tracked then a click to enter the conversation
user = driver.find_element_by_xpath("//span[@title = '{}']".format(name))
user.click()

while True:
   # in the conversation page, a span with title online is diplayed when user is online.
   #the web driver will wait 8hrs=28800s, if user not online all this time script will be killed by webdriverWait
   element = WebDriverWait(driver, 28800).until(
      EC.visibility_of_element_located(
         (By.XPATH, "//span[@title = 'online']")))

   #Moment the user came online
   now = datetime.datetime.now()
   print("online at : ")
   print(now.strftime("%H:%M:%S"))

   element = WebDriverWait(driver, 28800).until(
      EC.invisibility_of_element_located(
         (By.XPATH, "//span[@title = 'online']")))

   #Moment the user went offline
   now = datetime.datetime.now()
   print("offline at : ")
   print(now.strftime("%H:%M:%S"))
   print("************")

我的脚本可以工作,但是,我希望它运行几个小时,比如8小时甚至更长时间,但我读到使用坏实践时使用WebDriverWait的时间很长(在我的例子中是28800秒)。

,那么还有其他更好的方法来实现这一点吗?

如何将输出写入txt或word文件?

有让我的代码更好的建议吗?

如何防止CPU猛击?或任何可能发生的问题

EN

Stack Overflow用户

发布于 2021-07-22 21:19:20

我要建议的是,在您的程序中,每次执行此程序时都需要扫描whatsapp,只需替换这一行。

driver = webdriver.Chrome('C:/webdrivers/chromedriver.exe')

有了这个

代码语言:javascript
运行
复制
driver = webdriver.Chrome('C:/webdrivers/chromedriver.exe', options="user-data-dir=C:\\Users\\<username>\\AppData\\Local\\Google\\Chrome\\User Data\\whtsap")

这样你就需要扫描QR,但只需要扫描一次。

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54246168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档