我试图使用" whatsapp -web“、"selenium”和"python 3“来了解whatsapp用户何时上线或离线。
为了解释更多,我希望脚本工作如下:
脚本将侦听要显示的span (带有title=online),当span显示时(这意味着用户在线),我希望此时打印时间,然后脚本将继续侦听以使span消失,当脚本消失时,脚本打印消失的时间,等等。
这是我的密码:
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猛击?或任何可能发生的问题
发布于 2021-07-22 21:19:20
我要建议的是,在您的程序中,每次执行此程序时都需要扫描whatsapp,只需替换这一行。
driver = webdriver.Chrome('C:/webdrivers/chromedriver.exe')
有了这个
driver = webdriver.Chrome('C:/webdrivers/chromedriver.exe', options="user-data-dir=C:\\Users\\<username>\\AppData\\Local\\Google\\Chrome\\User Data\\whtsap")
这样你就需要扫描QR,但只需要扫描一次。
https://stackoverflow.com/questions/54246168
复制相似问题