【问题标题】:Loop through array of shuffled WebElements without them getting stale循环遍历洗牌的 WebElement 数组,而不会过时
【发布时间】:2017-06-22 01:40:31
【问题描述】:

我的困境是,如果我使用

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,但我不知道它是否会起作用。编辑:会产生一个无限循环,因为一旦全部被点击,我将是零,它永远不会退出。

我知道代码已经过广泛的测试,但是,机器人因为不像人类和随机而被禁止。这个脚本的基础是遍历一个类别列表,然后遍历一个类别中的所有卡片。尝试随机化类别但类似的困境,因为要刷新列表,您必须像上面的块一样在每个循环中重新制作数组,然后会再次单击已完成类别的问题......任何建议将不胜感激。

【问题讨论】:

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

标签: python arrays loops selenium


【解决方案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

(以上原因很明显,未经测试)

【讨论】:

    猜你喜欢
    • 2021-12-25
    相关资源
    最近更新 更多