繁体   English   中英

Python Selenium:遍历动态元素

[英]Python Selenium: Iterating through a dynamic element

我敢肯定,这可能以前被问过,但我还没有遇到过。 如果它已经在这里,我很抱歉。 但是,我在试图弄清楚逻辑时遇到了问题:该页面以我希望单击的元素列表(开始 20 个)开始。 滚动后,会显示更多相同的元素。 我在滚动后与加载的元素进行交互时遇到问题。 到目前为止,这是我想出的:

def clix():
chazz = driver.find_elements_by_css_selector("button[class^='message-anywhere']")
for x in chazz:
    if x.is_displayed():
            x.click()
            time.sleep(1)
            driver.find_element_by_css_selector("button[data-control-name^='overlay.close']").click()
            time.sleep(2)

scrollz()
def scrollz():
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
    time.sleep(4)
    clix()
clix()

我知道这不是应该的“pythonic”或“最佳实践”。 我只是担心功能。 任何见解将不胜感激。 driver.find_element_by_css_selector("button[data-control-name^='overlay.close']").click()按钮仅用于弹出 window。

谢谢

html:

<button class="message-anywhere-button artdeco-button artdeco-button--secondary artdeco-button--2" aria-label="Send message to Abarna Rajkumar" data-ember-action="" data-ember-action-63="63">
    Chat
</button>

我认为只有一个 function 可以解决您的问题。我可能错了,因为我没有正在测试的应用程序。

  • 诱导WebDiverWait并等待visibility_of_all_elements_located ()
  • 迭代时使用location_once_scrolled_into_view然后单击。
  • 诱导WebDiverWait并等待element_to_be_clickable () 点击关闭按钮

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def clix():
 chazz =WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"button[class^='message-anywhere']")))
 for x in range(len(chazz)):
    chazz = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "button[class^='message-anywhere']")))
    chazz[x].location_once_scrolled_into_view
    chazz[x].click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button[data-control-name^='overlay.close']"))).click()

clix()

chazz = driver.find_elements_by_css_selector("button[class^='message-anywhere']") global xx xx = 0 def clix(): global xx print (xx) chazz = driver.find_elements_by_css_selector("button[class^='message -anywhere']") while xx < len(chazz): print(xx)

    chazz[xx].click()
    time.sleep(1)
    driver.find_element_by_css_selector("button[data-control-name^='overlay.close']").click()
    time.sleep(1)

    xx = xx+1

driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
xx = xx+1

我 = 0

while i < 1000:
    clix()

如果我真的想将它运行到无穷大......我只需将while循环设置为无法实现的东西......而i < -1...... fox示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM