Retrieve specific elements from a loop

I need help with a Python for loop that prints values ranging from 3 to 42.5. However, I am looking to store only the values between 1 and 8 in a variable.

with requests.Session() as s:
  r = s.get(url, headers=headers)
  soup = BeautifulSoup(r.text, 'html.parser')
  sizes = soup.findAll(True,{'class':'product__sizes-size-1'})
  for allsize in sizes:
    print(allsize.text)

The current output includes values such as

3 4 4.5 5 5.5 6 6.5 7 8 36 37.5 38 38.5 39 40 40.5 41 42.5

Could someone guide me on how to assign a variable specifically to values within the range of 1 to 8?

Answer №1

Here's a possible solution:

using requests.Session() as session:
  response = session.get(url, headers=headers)
  parsed_html = BeautifulSoup(response.text, 'html.parser')
  valid_sizes = [size for size in parsed_html.findAll(True, {'class':'product__sizes-size-1'}) if float(size.text) >= 1 and float(size.text) <= 8]

  for s in valid_sizes:
    print(s.text)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having a tough time getting Selenium to successfully complete the automated checkout process

After experimenting with Selenium and attempting to automate the checkout process, I've encountered a stumbling block in the final part of my code. Despite numerous configurations of 'sleeps' and 'implicit_waits', I keep receiving ...

Issue encountered while attempting to read data frame dictionary: TypeError - string indices must be integers, not str

Currently, I am attempting to extract a list of columns and corresponding values from a nested dictionary data frame column. The structure of the Data Frame column is as follows: {"id":"0","request":{"plantSearch":"true","maxResults":"51","caller":"WMS", ...

Developing a Python serverless function on Vercel using Next.js is a streamlined

Discovering the capability of using Python to create a serverless function within a Next.js project was truly exciting. Once deployed on Vercel, it seamlessly transforms into a serverless function. Browsing through the documentation, I stumbled upon a str ...

Other Jupyter Notebooks will not begin on the subsequent open port

When utilizing Jupyter Notebook on Windows 10 and opening multiple notebooks, each one would launch on the next available port (the first on port 8888, the second on 8889, etc.). However, after installing Anaconda on Windows Subsystem for Linux (WSL), I en ...

Combine an array with a JSON object in Python

Working with JSON in python3 and looking to add an array to a json object. Here's what I have so far: values = [20.8, 21.2, 22.4] timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] myJSON = '{ Gateway: {"serial ...

What is the best way to utilize the data in a file as a parameter?

I recently installed AutoKey on my computer with the intention of being able to run python scripts using keyboard shortcuts. Specifically, I wanted to create a script that would simulate pressing the "d" key followed by the "s" key in a loop, with the abil ...

Is there a Python framework that specializes in serving images?

My iOS app project requires a backend server capable of efficiently handling image files and dynamic operations like interacting with a data store such as Redis. Python is my preferred language for the backend development. After exploring various Python w ...

What is preventing this function from displaying the expected output?

def checkStraight(playerHand): playerHand.sort() print(playerHand) for i in range(len(playerHand)-1): if playerHand[i] != playerHand [i+1] - 1: handStrength = 0 return False break else: ...

Unable to establish a connection to the Flask webserver

Testing my code on Visual Studio 2017 with the file named test: from flask import Flask, request #import main Flask class and request object from test import app app = Flask(__name__) #create the Flask app @app.route('/query-example') def ...

struggling to open a csv file using pandas

Embarking on my journey into the world of data mining, I am faced with the task of calculating the correlation between 16 variables within a dataset consisting of around 500 rows. Utilizing pandas for this operation has proven to be challenging as I encoun ...

Smooth Exponential Averaging

While browsing this website to gain a better understanding of exponential smoothing averages, I came across a section of code that confused me. import pandas, numpy as np ewma = pandas.stats.moments.ewma # create a hat function and introduce noise x = np ...

"Configuration options" for a Python function

Not sure what to title this, but look at the example below: def example(): """ Good """ pass If I were to print example.__doc__, it would display " Good ". Is it possible to create additional 'variables' like this for other purposes? ...

Analyzing GC log files with python programming language

Recently started learning Python with the goal of creating tools to streamline daily tasks. I have a log file that contains heap memory details at specific time stamps. For example: ####<2020/04/21 00:00:00.977 +0200> <XYZ> <123> <14 ...

Tips for removing rows in a pandas dataframe by filtering them out based on string pattern conditions

If there is a DataFrame with dimensions (4000,13) and the column dataframe["str_labels"] may contain the value "|", how can you sort the pandas DataFrame by removing any rows (all 13 columns) that have the string value "|" in them? For example: list(data ...

Exploring the Power of Strings in Python

I have encountered a challenge - I need to develop a program that prompts the user for their first name, saves it, then asks for their last name and does the same. The final task is to display the first name and last name in two separate rows as shown belo ...

Converting data into a hierarchical structure for a JSON file

Can someone assist me in parsing this specific file for the Gene Ontology (.obo)? I need guidance on how to accomplish this task. I am currently working on a project that involves creating a visualisation in D3. To achieve this, I require a JSON format "t ...

Python script for extracting content from iframes without specified sources

Currently, I am attempting to extract the content within an iFrame with the ID "topic" from the following HTML file: https://i.stack.imgur.com/FustQ.png Even after trying methods like Selenium and Beautiful Soup, I am still unable to access the elements i ...

There is an unbound local error popping up in the script I created using Selenium for my user

I am facing an issue with a program that scrapes data from a web app. The program is running fine on my computer, but the user keeps encountering an unbound local error in the box_input method. Here is the error screenshot sent by the user. I'm unsur ...

Choosing Checkboxes with Selenium

I'm attempting to utilize Selenium to interact with a checkbox, as indicated in the HTML image. The issue is that all four options have the same checkbox input tag, and their unique identifier is only specified by the id="country_england" .. ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...