首页 > 解决方案 > 如何使用 Python Selenium 在网站上滚动内部滚动条?

问题描述

尝试在具有自己滚动条的框内滚动。尝试了许多方法都失败或不够好。

这是滚动条的html

<div id="mCSB_2_dragger_vertical" class="mCSB_dragger" style="position: absolute; min-height: 30px; display: block; height: 340px; max-height: 679.6px; top: 0px;" xpath="1"><div class="mCSB_dragger_bar" style="line-height: 30px;"></div></div>

当“顶部”值上升或下降时允许滚动。滚动条当然也会下降。一直试图模仿这一点,但无济于事

到目前为止的一些尝试

    scrollbar =driver1.find_element(By.XPATH,"//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']")

    A = ActionChains(driver1).move_to_element(scrollbar)
    A.perform()
    A = ActionChains(driver1)
    A.perform()
    W = driver1.find_element(By.CSS_SELECTOR,".visible-list > .row:nth-child(4)> .investment-item")
    W.location_once_scrolled_into_view

    scrollbar =driver1.find_element(By.XPATH,"//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']").get_attribute("style")
    newscrollbar = str(scrollbar).replace("top: 0px","top: -100px")
    driver1.find_element(By.XPATH,"//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']").__setattr__("style",newscrollbar)

    scrollbar =driver1.find_element(By.XPATH,"//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']").get_attribute("style")
    newscrollbar = str(scrollbar).replace("top: 0px","top: -100px")
    A = driver1.create_web_element(newscrollbar)
    driver1.find_element(By.XPATH,"//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']").__setattr__("style",A)

Iv 尝试了更多方法,但无济于事..this link 提供了更多详细信息

通过使用 Selenium Python 编辑属性来使用滚动条

先感谢您

这里有一些方法可以看到它

    A = driver1.find_element(By.XPATH,"//div[@id='mCSB_2_dragger_vertical']").get_attribute("style")
    print(A) #willReturnEg:position: absolute; min-height: 30px; display: block; height: 537px; max-height: 855px; top: 0px;
    Newstyle = str(A).replace("top: 0px;","top: 80px;")
    driver1.__setattr__("style",Newstyle)

获取样式属性。将其更改为字符串,例如: ...top:100px .... 设置网站上的帖子属性

标签: pythonhtmlcssselenium-webdriver

解决方案


您需要确保引用正确的元素,所以,也许这就是您尝试了各种方法但没有一种方法适合您的原因。一旦你确定你对你的元素有正确的句柄,那么使用正确的元素选择进行操作很容易,我会使用javascript。只需插入此代码:

 xpath_element = "//aside[@class='sidebar mCustomScrollbar _mCS_2']//div[@class='mCSB_container']"
 fBody = driver1.find_element_by_xpath(xpath_element)
 scroll = 0
 while scroll < 3:  # this will scroll 3 times
     driver1.execute_script('arguments[0].scrollTop = arguments[0].scrollTop + arguments[0].offsetHeight;',
                                 fBody)
      scroll += 1
      # add appropriate wait here, of course. 1-2 seconds each
      sleep(2)

推荐阅读