Selenium中element.text获取过慢及耗时波动的问题咨询
问题与解决方案
环境信息
- Chrome版本:105.0.5195.102
- Selenium == 4.4.3
- Python == 3.9.12
核心问题
- 在页面中调用
element.text获取文本耗时约0.x秒,速度难以接受。原以为element.text是直接从缓存页面读取文本,无法理解为何耗时如此之久。如何仅通过Selenium提升该操作的速度? - 为何每次调用
element.text的耗时都不相同?
注:已排除使用BeautifulSoup、lxml等第三方解析库的方案,需仅用Selenium解决。
问题解释与解决方案
为什么element.text耗时高且不稳定?
element.text并不是直接读取本地缓存的文本。当你调用这个方法时,Selenium会向Chrome发送指令,浏览器需要完成一系列操作:遍历目标元素及其子元素、根据可见性和CSS样式过滤文本、合并格式化内容,最后通过ChromeDriver把结果返回给Python进程。这个过程涉及跨进程通信,且浏览器主线程可能同时处理页面渲染、异步请求、垃圾回收等任务,导致每次执行的耗时存在波动。
仅用Selenium提升速度的方法
直接通过execute_script在浏览器端执行JavaScript获取文本,减少跨进程通信的开销,这是最快的纯Selenium方案:
- 若要和
element.text行为完全一致(仅获取可见文本),使用innerText:
txt = wd.execute_script('return arguments[0].innerText;', e)
- 若无需考虑可见性,想获取所有文本内容(包括隐藏元素的文本),使用
textContent,速度会更快:
txt = wd.execute_script('return arguments[0].textContent;', e)
优化后的示例代码
import chromedriver_autoinstaller import time from selenium import webdriver from selenium.webdriver.common.by import By chromedriver_autoinstaller.install(cwd=True) options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument('--no-sandbox') options.add_argument('--ignore-certificate-errors') options.add_argument('--disable-dev-shm-usage') options.add_experimental_option("excludeSwitches", ["enable-logging"]) wd = webdriver.Chrome(options=options) wd.get("https://www.bbc.com/") t0 = time.time() e = wd.find_element(By.CSS_SELECTOR, "#page > section.module.module--header > h2") print(f"定位元素耗时: {time.time()-t0:.4f}秒") print("\n使用element.text的耗时:") for i in range(3): t0 = time.time() txt = e.text print(f"第{i+1}次: {time.time()-t0:.4f}秒") print("\n使用execute_script(innerText)的耗时:") for i in range(3): t0 = time.time() txt = wd.execute_script('return arguments[0].innerText;', e) print(f"第{i+1}次: {time.time()-t0:.4f}秒") wd.quit()
内容的提问来源于stack exchange,提问作者sssbbbaaa
相关产品推荐
相关产品推荐

