【问题标题】:Python Selenium Chromedriver horizontal scroll not workingPython Selenium Chromedriver水平滚动不起作用
【发布时间】:2018-05-02 13:04:34
【问题描述】:

我正在使用 Python 中的 Selenium Chromedriver 进行网页抓取。现在,当我尝试获取数据时,对于一个网格(可水平滚动),我只能在浏览器中看到网格的可见部分。

例如。在这里,我只能获取数据直到 Part Category ,就像这样 ['', '', '', '', '', 'Item Number', 'Item Description', 'Lifecycle Phase', 'Old Lifecycle Phase', 'Docs Rqd', 'PGDS Audit', 'Part Category', '', '', '', '', '', '', '', '', '', '', '', '', ''] 虽然确实存在更多的列。

我试过 actions.move_to_elementdriver.execute_script 但没有工作。 这是我的示例代码

for i in range(len(titles)):
    current_tab = driver.find_elements_by_xpath("//div[@id='tabsDiv']/ul/li/a")[i:i+1]
    current_tab_name=current_tab[0].text
    current_tab[0].click()
    time.sleep(5)
    if(current_tab_name=='Affected Items'):
        current_tab_info=driver.find_elements_by_xpath("//div[@class='GMHeadMid']/table[@class='GMSection']/tbody/tr[@class='GMHeaderRow']/td") ## this is the scroll-able grid  
        driver.execute_script("window.scrollTo(0, 100)")
        #current_tab_info[0].location_once_scrolled_into_view
        #actions = ActionChains(driver)
        #actions.move_to_element(current_tab_info[0]).perform()
        current_tab_header_list=[x.text for x in current_tab_info]
        print(current_tab_header_list)

【问题讨论】:

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


    【解决方案1】:

    为什么不让驱动滚动到元素而不是水平滚动?

    scrollToElement = "arguments[0].scrollIntoView()"
    
    driver.execute_script(scrollToElement, current_tab_info)
    

    我不是 python 期望,所以我的语法可能有问题。

    【讨论】:

    • 是的,但没有运气。仍然只获得可见列
    【解决方案2】:

    终于有办法了

    # First of all get all the header column span IDs
    current_tab_info = driver.find_elements_by_xpath("//div[@class='GMHeadMid']/table[@class='GMSection']/tbody/tr[@class='GMHeaderRow']/td/div/span")
    current_tab_header_list = [x.get_attribute('id') for x in current_tab_info]
    
    # Then get element text against each ID
    current_tab_header_label_list =[]
            for i in current_tab_header_list:
                # will scroll until that element is not appeared on page
                current_header_info = driver.find_elements_by_xpath(
                    "//div[@class='GMHeadMid']/table[@class='GMSection']/tbody/tr[@class='GMHeaderRow']/td/div/span[@id='"+str(i)+"']")
                driver.execute_script("arguments[0].scrollIntoView(true);", current_header_info[0])
                current_tab_header_label_list.append(current_header_info[0].text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 2013-06-29
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多