Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环遍历经过洗牌的WebElements数组,而不会使它们过时_Python_Arrays_Loops_Selenium - Fatal编程技术网

Python 循环遍历经过洗牌的WebElements数组,而不会使它们过时

Python 循环遍历经过洗牌的WebElements数组,而不会使它们过时,python,arrays,loops,selenium,Python,Arrays,Loops,Selenium,我的困境是如果我使用 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")
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
这张卡的问题是i变量,因为由于每个循环都有洗牌,所以可以单击同一张卡。然后,我添加了一个catch来检查卡是否已经被点击,如果已经被点击,则继续。听起来这是可行的,但遗憾的是,i变量对这些进行计数,然后最终通过索引进行计数。我曾考虑过周期性地将I设置回1,但我不知道它是否有效。编辑:将使一个无限循环,因为一旦所有点击我将是零,它将永远不会退出


我知道代码是有效的,它经过了广泛的测试,但是,机器人因为不象人类和随机性而被禁止。这个脚本的基础是遍历一个类别列表,然后遍历一个类别中的所有卡片。尝试对类别进行随机化,但遇到类似的难题,因为要刷新列表,您必须在每个循环中重新生成数组,如上图所示,然后出现已完成类别的问题,将再次单击。。。任何建议都将不胜感激。

这里发生的事情是,当您与页面交互时,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

(由于明显的原因,上述内容未经测试)

能否显示确定卡是否已被单击的代码?我认为你只需要在那里增加更多的条件。(1) 添加最大循环数。(2) 设置i=i-1。@Buaban如果在下一步中被“监视”: