首页 > 解决方案 > python selenium,慢 xpath '所有元素'。添加超时

问题描述

我需要获取页面上的所有元素并遍历它们以搜索每个元素。

目前我正在使用,driver.find_elements_by_xpath('//*[@*]')

但是,在较大的页面上完成上述代码行可能会有延迟。有没有办法以 100 个元素为增量检索结果?或者至少添加一个超时?

在多线程内终止driver.find_elements_by_xpath('//*[@*]')是我目前认为我可以解决这个问题的唯一原因。

我需要找到页面上包含某些字符串的所有元素。例如。elem.get_attribute('outerHTML').find('type="submit"') != -1......等等等等......我还需要它们彼此接近来比较索引位置

谢谢!

标签: pythonseleniumxpath

解决方案


import Globalz          ###### globals import is an empty .py file
import threading
import time
import ctypes


def find_xpath():
    for i in range(5):
        print(i)
        time.sleep(1)
    Globalz.curr_value = 'DONE!'

    ### this is where the xpath retrieval goes (ABOVE loop is for example purposes only)



def stopwatch(info):
    curr_time = 0
    failed = False
    Globalz.curr_value = ''
    thread1 = threading.Thread(target=info['function'])
    thread1.start()
    while thread1.is_alive() is True:
        if curr_time >= info['timeout']: failed = True; ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread1.ident), ctypes.py_object(SystemExit))
        curr_time += 1; time.sleep(1)
    if failed is True: return info['failed_returns']
    if failed is False: return Globalz.curr_value


betty = stopwatch({'function': find_xpath, 'timeout': 10, 'failed_returns': 'failed'})
print(betty)

如果有人对此感兴趣,这是一个解决方案。我创建了一个名为 stopwatch() 的包装器


推荐阅读