如何对网页中的动态元素执行操作

时间:2019-07-09 22:31:17

标签: python selenium selenium-chromedriver

] 1我正在尝试自动在受欢迎的社交媒体网站上查看故事。点击每个关注者故事的最简单方法是什么?

   while True:
      time.sleep(3)
      WebDriverWait(driver, AWAIT_PRESENCE).until(EC.presence_of_element_located((By.XPATH, TARGET_FOLLOWERS_STORIES)))
      stories = driver.find_elements_by_xpath(TARGET_FOLLOWERS_STORIES)
      for story in stories:
          time.sleep(3)
          driver.execute_script("arguments[0].scrollIntoView();", story )
          driver.execute_script("arguments[0].click()", story)
          time.sleep(2)
          while True:
              try:
                  next_btn = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, TARGET_STORIES_NEXT)))
                  driver.execute_script("arguments[0].click()", next_btn)
                  time.sleep(1)
              except:
                  break

1 个答案:

答案 0 :(得分:0)

当您单击列表中的任何元素时,将刷新元素引用,并且硒无法从旧列表中找到元素。这就是为什么您得到staleElementException的原因。您只需要稍微调整一下代码即可解决此问题。始终获取故事的数量,并使用索引为 [index] 的xpath遍历故事。

while True:
      time.sleep(3)
      WebDriverWait(driver, AWAIT_PRESENCE).until(EC.presence_of_element_located((By.XPATH, TARGET_FOLLOWERS_STORIES)))
      stories = driver.find_elements_by_xpath(TARGET_FOLLOWERS_STORIES)
      for storyNumber in range(len(stories)): #<== updated this line
          time.sleep(3)
          story = driver.find_element_by_xpath(TARGET_FOLLOWERS_STORIES + "[" +str(storyNumber+1) + "]") #<== updated this line
          driver.execute_script("arguments[0].scrollIntoView();", story )
          driver.execute_script("arguments[0].click()", story)
          time.sleep(2)
          while True:
              try:
                  next_btn = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, TARGET_STORIES_NEXT)))
                  driver.execute_script("arguments[0].click()", next_btn)
                  time.sleep(1)
              except:
                  break