使用Selenium关闭实时聊天窗口及定位分页元素报错如何解决
问题原因&修复方案
1. 找不到分页元素报错原因
find_element_by_class_name方法仅支持传入单个类名,你传入的stamped-pagination stamped-reviews-ul是两个类名,该方法会将整体视为一个类名匹配,自然找不到元素。如果要匹配多个类名,可使用CSS选择器:.stamped-pagination.stamped-reviews-ul- 下一页按钮的XPath存在语法错误,你写的
"'//*[@id='stamped-reviews-tab']/ul/li[14]/a'"外层多了多余的单引号,直接导致匹配失败。同时写死li[14]的索引非常不稳定,不同页数下分页列表的长度会变化,应该通过特征匹配「>」按钮。 - 评论模块为异步加载,需要等模块渲染完成后再查找元素,直接调用
find_element很容易出现加载未完成的报错。
2. 无需点击关闭聊天窗口方案
不用切换iframe找关闭按钮,直接执行JS代码删除或隐藏聊天节点即可,稳定性更高,代码示例:
driver.execute_script("document.getElementById('gorgias-chat-container').remove();")
执行后会直接删除整个聊天窗口的DOM节点,不需要任何点击操作。
3. 完整修复代码(包含循环翻页到最后一页功能)
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(10) driver.get("https://everdeskplus.com/products/everdesk-max") wait = WebDriverWait(driver,30) # 关闭Spin弹窗 wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@id='pge_HN8znV-LA']/div[1]/span"))).click() # 直接删除聊天窗口,无需点击 wait.until(lambda d: d.execute_script("return document.getElementById('gorgias-chat-container') != null")) driver.execute_script("document.getElementById('gorgias-chat-container').remove();") # 等待评论模块加载,滚动到评论区 review_container = wait.until(EC.presence_of_element_located((By.ID, "stamped-reviews-tab"))) driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", review_container) time.sleep(2) # 等待评论内容渲染完成 # 循环翻页直到最后一页 while True: try: # 匹配下一页按钮,用title属性特征匹配 next_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.stamped-next a[title='Next page']"))) # 判断下一页按钮是否可点击(最后一页会加disabled类) if "disabled" in next_btn.get_attribute("class"): break next_btn.click() # 等待翻页后评论加载完成 wait.until(EC.staleness_of(next_btn)) time.sleep(1) except: # 找不到下一页按钮说明已经到最后一页 break # 后续爬取评论的逻辑...
内容的提问来源于stack exchange,提问作者Beaty
相关产品推荐
相关产品推荐

