簡體   English   中英

使用 python selenium 向下滾動以實現新元素的動態出現

[英]Scrolldown with python selenium to achieve dynamic appearing of new elements

Url 是https://donstroy.com/full-search 在那個頁面上,里面有父<div class="content">和 21 個<div class="item"> 當人類將鼠標懸停在<div class="content">並向下滾動時,會動態出現多個新的<div class="item">元素。

我試圖通過 selenium 來實現這個結果(出現新元素),但我只能得到前 21 個<div class="item">

我嘗試了不同的方法在 selenium 中向下滾動,但它們都沒有導致出現新的<div class="item">元素。 下面是我的代碼。 當我在 Element Inspector 的控制台中以純 javascript 運行它時,使用 scrollIntoView 的第一種方法運行良好(它會導致出現新元素),但仍然無法通過 selenium 運行。

import selenium.webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.action_chains import ActionChains

def parse_objs():
    return driver.find_elements_by_xpath('//div[@class="item"]')

options = Options()
options.headless = True
driver = selenium.webdriver.Firefox(options=options)
driver.set_page_load_timeout(300) # yes, it may take up to multiple minutes to load the page so may need to wait long time, it's normal
driver.get('https://donstroy.com/full-search')

objs = parse_objs()

# Amount of object on initial page load
print('Initial load : %s' % len(objs)) # prints 21 as expected

# Method 1
driver.execute_script('arguments[0].scrollIntoView();', objs[-1])
objs = parse_objs()
print('Method 1 : %s' % len(objs)) # expected to increase but still prints 21
#The thing is that when running the same method in pure javascript in Element Inspector's console, it's working fine:
#var objs=document.getElementsByClassName('item');
#objs[20].scrollIntoView();
#after that, amount of objs (objs.length) increases to 41 so it should work in selenium but it does not!

# Method 2
actions = ActionChains(driver)
actions.move_to_element(objs[-1]).perform()
objs = parse_objs()
print('Method 2 : %s' % len(objs)) # expected to increase but still prints 21

# Method 3
objs_container=driver.find_element_by_xpath('//div[@class="content"]')
driver.execute_script('arguments[0].scrollTop = 300;', objs_container)
print('ScrollTop=%s' % driver.execute_script('return arguments[0].scrollTop', objs_container)) # always returns 0 no matter what value i try to apply for scrollTop in above command
objs = parse_objs()
print('Method 3 : %s' % len(objs)) # expected to increase but still prints 21

driver.quit()

查看網站https://donstroy.com/full-search下一組元素僅在滾動結束后加載。 現在,使用您的所有方法,webdriver 似乎只讀取最初與頁面一起加載的前 21 個元素。 您可能想查看滾動是否正常工作,以便下一組元素動態顯示。 添加預期條件等待(EC),打印數據然后再次向下滾動,直到出現下一組數據。 重復此步驟,直到獲得所需的列表長度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM