【问题标题】:Fix: Lazy loading in Selenium Python修复:Selenium Python 中的延迟加载
【发布时间】:2020-08-22 02:38:38
【问题描述】:

由于延迟加载元素,Python 在可能的 100 个元素中只选择了 18 个元素,在页面加载时,只会加载 18 个,并且在滚动时将上传新元素,删除以前加载的元素,我该如何解决这个问题它将所有 100 个元素存储在 persons 列表中并单击其中的每一个元素。

DOM element structure of the page

d = 0
itr = 1
time.sleep(17)

while True:
    persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")
    print(len(persons))
    for i, person in zip(names, persons):
        time.sleep(4) 
        persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")
        if d >= len(persons):
            break
        i = names[d]
        person = persons[d]
        browser.execute_script("arguments[0].scrollIntoView(true);", person)
        time.sleep(3) 
        person.click()

【问题讨论】:

  • names 只是我从存储在代码块上方的名称变量中提取的列表,主要问题是人员延迟加载。
  • 您的代码中的一些事情并不清楚。比如变量 d 有什么用?因为它总是 0。所以你总是想点击列表中的第一个元素吗?假设您的要求是单击 browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']") 标识的所有元素。请参阅答案部分。
  • @rahulrai d的目的实际上是在迭代中点击d的当前值。 d 可以在 1 到 100 之间。选择右键单击。非常感谢。
  • 查看我提供的答案。我正在点击所有链接,您可以考虑并执行您的任务。

标签: python selenium loops lazy-loading


【解决方案1】:

点击页面上的所有元素,向下滚动后新元素正在加载并且旧元素正在消失。

while True:
    # Get screen height upon page loading for the first time 
    last_height = browser.execute_script("return document.body.scrollHeight")

    #Get the list of elements 
    persons = browser.find_elements_by_xpath("//*[@class='i-edit mrs no-text-decoration ember-view']")

    # Lopp through all elements and click on them
    for i in range (1,len(persons)+1):
        # As after every click page will be reloaded, getting fresh reference to element every time , so that wont get stale element exception
        linkXpath = "(//*[@class='i-edit mrs no-text-decoration ember-view'])["+str(i)+"]"
        WebDriverWait(browser, 30).until(EC.element_to_be_clickable((By.XPATH, linkXpath ))).click()
    # Scroll down to bottom
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)

    #Get new height of screen
    new_height = browser.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

【讨论】:

  • 以上应该可以。我无法像您一样在本地进行测试,也无法共享页面链接。如果有任何问题,请告诉我。
  • 如果它可以帮助您解决问题,请点赞。它会反过来帮助别人和我自己。干杯:)
猜你喜欢
  • 2017-01-01
  • 2022-01-19
  • 1970-01-01
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2011-03-14
相关资源
最近更新 更多