2017-06-22 55 views
0

我的困境是,如果我使用遍历洗牌WebElements的阵列没有他们获得旧

a=[] 
a=driver.find_elements_by_class_name("card") 
random.shuffle(a) 
for card in a: 
    nextup=(str(card.text) + '\n' + "_" * 15) 
    do a bunch of stuff that takes about 10 min 

第一轮作品,但后来我得到一个StaleElementException因为它点击链接,进入页面差异。于是我切换到这一点:

a=[] 
a=driver.find_elements_by_class_name("card") 
i=0 
cardnum=len(a) 
while i != cardnum: 
    i += 1 #needed because first element thats found doesnt work 
    a=driver.find_elements_by_class_name("card") #also needed to refresh the list 
    random.shuffle(a) 
    nextup=(str(card.text) + '\n' + "_" * 15) 
    do a bunch of stuff that takes about 10 min 

与这一个问题是我的变量,因为在同一张卡可以点击由于每次循环的洗牌。然后我添加了一个catch来检查卡片是否已经被点击,如果有卡片,继续。听起来像它会工作,但可悲的是,我变量计数这些,然后最终计数过去的指数。我想周期性地让我回到1,但我不知道它是否会起作用。编辑:会做一个无限循环,因为一旦所有点击,我将是零,它将永远不会退出。

我知道代码的工作原理已经被广泛测试,但是,机器人被禁止不被人类和随机使用。这个脚本的基础知识是通过一个类别列表,然后通过一个类别中的所有卡片。试图随机化的类别,但类似的困境,因为刷新列表,你必须在每个循环像上述块重做数组然后出现类别已完成的问题将再次点击...任何意见将不胜感激。

+0

你能显示确定卡片是否被点击的代码?我想你只需要在那里添加更多的条件。 (1)添加循环的最大数量。 (2)设i = i-1。 – Buaban

+0

@Buaban如果“看”在nextup: –

回答

0

这里发生的事情是,当您与页面交互时,DOM会被刷新,最终导致您存储的元素过时。

而不是保持元素的列表,请参考他们的个人元素路径,并根据需要重新获取的元素:

# The base css path for all the cards 
base_card_css_path = ".card" 

# Get all the target elements. You are only doing this to 
# get a count of the number of elements on the page 
card_elems = driver.find_elements_by_css_selector(base_card_css_path) 

# Convert this to a list of indexes, starting with 1 
card_indexes = list(range(1, len(card_elems)+1)) 

# Shuffle it 
random.shuffle(card_indexes) 

# Use `:nth-child(X)` syntax to get these elements on an as needed basis 
for index in card_indexes: 
    card_css = base_card_css_path + ":nth-child({0})".format(index) 
    card = driver.find_element_by_css_selector(card_css) 
    nextup=(str(card.text) + '\n' + "_" * 15) 
    # do a bunch of stuff that takes about 10 min 

(以上是未经考验的原因很明显)

+0

感谢这工作 –