我正在尝试使用 selenium python 向下滚动到 Whatsapp 网页聊天列表中的最后一个联系人。
我收到以下错误消息:
selenium.common.exceptions.JavascriptException: Message: javascript error: arguments[0].scrollIntoView is not a function
(Session info: chrome=90.0.4430.212)
有时:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=90.0.4430.212)
这是代码:
#Trial 1
# driver.execute_script("window.scrollTo(0, 1000);")
#Trial 2
# html = driver.find_element_by_tag_name('html')
# html.send_keys(Keys.END)
#Trial 3
# driver. execute_script("window.scrollTo(0,document.body.scrollHeight)")
#Trial 4
#This class is related to the side div
# test2 = driver.find_element_by_xpath("//div[@class='_1C2Q3 F-0gY']")
# driver.execute_script('arguments[0].scrollIntoView();',test2) #tried this
# test2.send_keys(Keys.PAGE_DOWN) # and also this
#Trial 5
#This class is related to the contacts
recentList = driver.find_elements_by_xpath("//span[@class='N2dUK']")
# driver.execute_script('arguments[0].scrollIntoView()',recentList) #tried this
for list in recentList :
# driver.execute_script("arguments[0].scrollIntoView();", list[:-1] )
# driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', list)
# time.sleep(1)
# driver.execute_script("window.scrollTo(0, 500);")
# print('RECENT LIST')
print(list.text)
我的问题:
如何在whatsapp网页中滚动到聊天列表的末尾
我在whatsapp 中也遇到同样的问题。我用这段代码解决了:
driver.find_element(By.ID, 'pane-side').send_keys(Keys.PAGE_DOWN)
我发送了完整的代码,我测试了它并且它有效:
导入库:
import tempfile
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
逻辑基础:
driver = webdriver.Firefox()
driver.get('https://web.whatsapp.com/')
driver.maximize_window()
time.sleep(25)
phone=[]
date=[]
msg=[]
SCROLL_PAUSE_TIME = 5.5
while True:
elements = WebDriverWait(driver,40).until(lambda driver:driver.find_elements(By.XPATH,'//div[@class="lhggkp7q ln8gz9je rx9719la"]'))
#driver.find_element(By.XPATH, './/div[@class="g0rxnol2 _3fGK2"]').send_keys(Keys.PAGE_DOWN)
driver.find_element(By.ID, 'pane-side').send_keys(Keys.PAGE_DOWN)
rep=0
for element in elements:
#print(interesado)
elem1 = element.find_element(By.XPATH, './/div[@class="_21S-L"]').text
#print(contenido1)
if elem1 not in phone:
phone.append(elem1)
print(elem1)
elem2=element.find_element(By.XPATH, './/span[@class="aprpv14t"]').text
date.append(elem2)
#print(elem2)
elem3=element.find_element(By.XPATH, './/div[@class="vQ0w7"]').text
msg.append(elem3)
#print(elem3)
else:
rep+=1
time.sleep(SCROLL_PAUSE_TIME)
if rep > 2:
print('exit infinite loop')
break
打印结果:
import pandas as pd
result=[phone,date,msg]
df=pd.DataFrame(result).T
print(len(phone))
print(phone)
df.columns=['PHONE','DATE','MESSAGE']
df
尝试下面的代码:
driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")