随机单击所有选项卡以获得无限量

时间:2017-11-03 07:20:46

标签: python css selenium xpath selenium-webdriver

我正在尝试随机点击此page上的所有未打开的标签(元素)。

不幸的是,下面的方法很有用,使用这种方法似乎并没有点击所有元素。我假设由于某种原因它不喜欢索引中的索引(或者没有正确地加载所有索引)。添加while True:,往往会解决这个问题,但我不确定如何无限量地随机化。有什么想法吗?

options = driver.find_elements_by_xpath('//*[@class="KambiBC-mod-event-group-header__event-count"]')

indexes = [index for index in range(len(options))]
shuffle(indexes)
for index in indexes:
    time.sleep(1)
    clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//*[@class="KambiBC-mod-event-group-header__event-count"])[%s]' % str(index + 1))))
    driver.execute_script("arguments[0].scrollIntoView();", clickMe)
    clickMe.click()
    time.sleep(1)

添加while True:

while True:
    time.sleep(0)
    #clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//*[@class="KambiBC-mod-event-group-header__event-count"])[%s]' % str(index + 1))))
    clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '(//*[@class="KambiBC-mod-event-group-header__event-count"])[%s]' % str(index + 1))))
    driver.execute_script("arguments[0].scrollIntoView();", clickMe)
    clickMe.click()
    time.sleep(0)

1 个答案:

答案 0 :(得分:1)

并非所有选项同时出现,但它们是逐个添加的。

您需要等到所有选项都可用。

尝试以下代码:

def get_options_length():
    list_length = len(wait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@class="KambiBC-collapsible-header KambiBC-mod-event-group-header"]'))))
    while True:
        time.sleep(1)
        if list_length == len(driver.find_elements_by_xpath('//*[@class="KambiBC-collapsible-header KambiBC-mod-event-group-header"]')):
            break
        else:
            list_length = len(driver.find_elements_by_xpath('//*[@class="KambiBC-collapsible-header KambiBC-mod-event-group-header"]'))
    return list_length

indexes = [index for index in range(get_options_length())]
shuffle(indexes)
for index in indexes:
    time.sleep(1)
    clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//*[@class="KambiBC-collapsible-header KambiBC-mod-event-group-header"])[%s]' % str(index + 1))))
    clickMe = clickMe.find_element_by_xpath('.//span')
    driver.execute_script("arguments[0].scrollIntoView();", clickMe)
    clickMe.click()