【问题标题】:How to scroll horizontally using selenium chromedriver in python如何在 python 中使用 selenium chromedriver 水平滚动
【发布时间】:2020-05-31 16:38:11
【问题描述】:

我正在使用 Python 中的 Selenium Chromedriver 进行网络抓取。我的链接如下:https://www.macrotrends.net/stocks/charts/AAPL/apple/balance-sheet

我想在链接中获取表格的数据。但是表格有一个滚动条,所以我只能在表格的可见列中获取数据。我想获取表格的所有数据。

例如)

driver.find_element_by_css_selector('#columntablejqxgrid').text

我的目标)

Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30
2013-09-30
2012-09-30
2011-09-30
2010-09-30
2009-09-30
2008-09-30
2007-09-30
2006-09-30
2005-09-30

结果)

Annual Data | Millions of US $ except per share data
2019-09-30
2018-09-30
2017-09-30
2016-09-30
2015-09-30
2014-09-30

所以,我必须水平滚动表格并获取其余数据。我怎样才能做到这一点?

【问题讨论】:

    标签: python-3.x selenium web-scraping


    【解决方案1】:

    对于滚动,您可以使用 ActionChains 类

    from selenium.webdriver.common.action_chains import ActionChains
    

    然后你可以使用类似的东西移动滑块

    ActionChains(driver).click_and_hold(slider).move_by_offset(x , 0).release().perform()
    

    这是一个适合您的解决方案:

    horizontal_bar_width = driver.find_element_by_id('jqxScrollOuterWraphorizontalScrollBarjqxgrid').rect['width']
    slider = driver.find_element_by_id('jqxScrollThumbhorizontalScrollBarjqxgrid')
        header_columns = []
    
    # Using iteration as span values won't show went they are hidden
    for _ in range(4):
        for el in driver.find_elements_by_css_selector('#columntablejqxgrid [role="columnheader"] span'):
            if el.text not in header_columns and el.text != '':
                header_columns.append(el.text)
        # Ensure the slider is in view
        slider.location_once_scrolled_into_view
        ActionChains(driver).click_and_hold(slider).move_by_offset(horizontal_bar_width/4, 0).release().perform()
    

    输出

    ['Annual Data | Millions of US $ except per share data',
     '2019-09-30',
     '2018-09-30',
     '2017-09-30',
     '2016-09-30',
     '2015-09-30',
     '2014-09-30',
     '2013-09-30',
     '2012-09-30',
     '2011-09-30',
     '2010-09-30',
     '2009-09-30',
     '2008-09-30',
     '2007-09-30',
     '2006-09-30',
     '2005-09-30']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 2013-09-26
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多