【问题标题】:Selenium how to scroll down to get all the linkSelenium 如何向下滚动以获取所有链接
【发布时间】:2019-09-23 08:22:19
【问题描述】:

我想导出所有的文档,所以我需要所有的链接。

如果鼠标不向下滚动,则不会加载所有链接。

需要向下移动一点才能逐渐加载

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Configuration information
email = "187069474@qq.com"
password = "Huangbo1019@"

driver = webdriver.Chrome()
index_url = "https://testselenium.quip.com/BCWAOAUkg1v"
driver.get(url=index_url)
driver.find_element_by_xpath('//*[@id="header-nav-collapse"]/ul/li[9]/a').click()  # click login
time.sleep(1)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[1]/form/div/input').send_keys(email)  # input email
driver.find_element_by_xpath('//*[@id="email-submit"]').click()
time.sleep(1)
driver.find_element_by_xpath('/html/body/div/div/form/div/input[2]').send_keys(password)  # input password
driver.find_element_by_xpath('/html/body/div/div/form/button').click()
time.sleep(2)

可能需要新策略

【问题讨论】:

标签: python selenium


【解决方案1】:

你可以直接用请求库试试

links = browser.find_elements_by_tag_name('a')
for link in links:
    try:
        requests.get(link.get_attribute('href'))

【讨论】:

    【解决方案2】:

    您可以使用 Javascript 按坐标滚动。如果您可以获取页面的高度(以像素为单位),则可以调用 Scroll(int xCoordinate, int yCoordinate) 方法并在每次连续滚动时增加滚动坐标。

    您希望首先滚动到页面上的初始 x,y 坐标。当您向下滚动时,您要滚动到的 y 坐标将发生变化。如果您在向下滚动时不增加 y 坐标,您将一遍又一遍地滚动到同一个位置。因此,您应该根据您正在使用的页面的像素高度来确定您的increment 变量。根据您要一次滚动的行数,您的 increment 变量应该大约等于您滚动过去的每个“行”的像素高度。

    numberOfScrolls 应该等于您希望滚动的行数。

    方法看起来像这样:

    public void ScrollDown(int startX, int startY, int increment, int numberOfScrolls) 
    {
        // cast webdriver to javascript executor
        var executor = ((IJavaScriptExecutor) driver);
    
        // keep track of current y coordinate
        // since we are scrolling down, y coordinate will change with each scroll
        var currentYCoordinate = startY;
    
        // scroll down in a loop
        for (int i = 0; i < numberOfScrolls; i++)
        {
            // scroll down
            executor.ExecuteScript("window.scrollTo(startX, currentYCoordinate);");
    
            // todo: implement any FindElement methods to get the new elements which have been scrolled into view.
    
            // update y coordinate since we just scrolled down
            currentYCoordinate = currentYCoordinate + increment;
    
         }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2018-01-03
      • 2021-04-16
      • 2016-01-13
      • 2016-12-06
      • 2019-03-29
      • 1970-01-01
      • 2019-07-07
      • 2017-11-06
      相关资源
      最近更新 更多