Home > other >  How to display a certain amount of information. Python 3
How to display a certain amount of information. Python 3

Time:03-25

How to display a certain amount of information. I am using selenium

I have 15 items displayed (there are 15 on the page). And I need to limit the amount of output information

(My English is bad)

from selenium import webdriver
from selenium.webdriver.common.by import By

import time

driver = webdriver.Chrome(executable_path="D:\\VSProjects\\iwantgamessel\\chromedriver.exe")
url = "..."
driver.get(url=url)

with open('...') as f:
    content = f.readlines()

try:
    time.sleep(10)
    divs = driver.find_elements(By.CLASS_NAME, "game-info")
    for div in divs:
        atag = div.text
        for x in content:
            print(x   "\n"   atag)
        
    
finally:
    f.close()
    driver.quit()

CodePudding user response:

In case you know there are 15 elements there while you want to get only 10 or 7 of them you can use indexing of the list you are iterating over. As following:

limit = 10
with open('...') as f:
    content = f.readlines()

try:
    time.sleep(10)
    divs = driver.find_elements(By.CLASS_NAME, "game-info")
    for idx, div in enumerate(divs):
        if idx < limit:
            atag = div.text
            for x in content:
                print(x   "\n"   atag)

CodePudding user response:

To restrict the amount of information you can use list slicing as follows:

  • To collect all the elements:

    divs = driver.find_elements(By.CLASS_NAME, "game-info")[::]
    
  • To collect the first five elements:

    divs = driver.find_elements(By.CLASS_NAME, "game-info")[:5]
    
  • To collect the alternative elements:

    divs = driver.find_elements(By.CLASS_NAME, "game-info")[::2]
    
  • To collect the last elements:

    divs = driver.find_elements(By.CLASS_NAME, "game-info")[:-5:-1]
    
  • Related