You need to get the string of each individual link, not of the whole result set.

Loop over the set and fetch .string per element:

[link.string for link in item.find_all('a')]
Answer from Martijn Pieters on Stack Overflow
๐ŸŒ
Readthedocs
sdss-marvin.readthedocs.io โ€บ en โ€บ 2.2.5 โ€บ tools โ€บ results โ€บ results_set.html
The ResultSet Object โ€” Marvin 2.2.5 documentation
Your query results come as a Marvin marvin.tools.results.ResultSet object. As ResultSet is sub-classed from a Python list, it behaves exactly as a Python list object. ResultSet contains a list of query results, where each item in the list is a Marvin ResultRow object.
Discussions

oracle database - Python - How to loop a ResultSet - Stack Overflow
I'm working with Python and JayDeBeApi to connect to a Oracle-type database. In the SELECT's statements I need to get about 10+ thousand of records. In the first time I done by using the "fetchAl... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Manipulating BeautifulSoup's ResultSet list object - Stack Overflow
I am trying to extract 2 pieces of data: 1) The value of the option element's "value" attribute (ie "01000.html" below). 2) The string that is within the tags (ie "Alabama"). There is limited information on the ResultSet list object that is created with I use More on stackoverflow.com
๐ŸŒ stackoverflow.com
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
The error tells you pretty much what you did wrong. Did you try reading it and applying what it tells you? In programming, you should learn to take all warnings and error messages seriously โ€” as in, actually read and understand them, not treat them as some random nonsense the computer throws at you that you're helpless to solve. More on reddit.com
๐ŸŒ r/learnpython
7
2
January 11, 2023
While attempting to iterate over a beautiful soup ResultSet, an exception is thrown: TypeError: 'ResultSet' object cannot be interpreted as an integer
Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you. I think I have detected some formatting issues with your submission: Python code found in submission text that's not formatted as code. If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting. Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here . More on reddit.com
๐ŸŒ r/learnpython
4
1
July 2, 2022
๐ŸŒ
DataCamp
campus.datacamp.com โ€บ courses โ€บ introduction-to-relational-databases-in-python โ€บ basics-of-relational-databases
Handling a ResultSet | Python
Once we have a ResultSet, we can use Python to access all the data within it by column name and by list style indexes.
๐ŸŒ
Dbtales
dbtales.com โ€บ convert-a-sql-query-result-to-a-list-in-python-mysql
Convert A SQL Query Result To A List In Python | MySQL โ€“ Database Tales
newlist = ['Houston'] newlist.append('Decentraland') ## append just 1 string newlist.append(string2[2]) ## append the 3rd value from another list newlist.append(number) ## append the entire number list print(newlist) For this sample I created a table called โ€œmyusersโ€ which includes the users first name, last name and the city they work in. In this example we are using a cursor and then querying this table for the (db tales com) first record and then all of them. Keep in mind that Python is returning a Tuple () for one record but then a List with many Tuples that contains our data, we are also querying 3 fields from the database.
๐ŸŒ
Zditect
zditect.com โ€บ blog โ€บ 21347757.html
ResultSet to list Python, Java convert ResultSet to list of Maps, Convert ResultSet to List scala, Groovy ResultSet to list, ResultSet array to List, ResultSet to object list java,
Approach #2 : using sorted() method Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable. As ResultSet is sub-classed from a Python list, it behaves exactly as a Python list object.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 58543028 โ€บ python-how-to-loop-a-resultset
oracle database - Python - How to loop a ResultSet - Stack Overflow
resultSet = self.do_select(sql, self.get_db_conn()) while resultSet.next(): entire_row_tuple = resultSet.getCurrent() #I don't know if this is possible in python #Do something with entire_row_tuple... Is this possible in python? Or, does exists a better way instead of using "fetchAll()" method? ... Check fetchOne() or fetchMany() - se e.g. here ยท โ€“ Marmite Bomber Commented Oct 24, 2019 at 16:41 ... Find the answer to your question by asking.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-35482.html
Parsing bs4 Resultset
November 8, 2021 - I'm having trouble understanding the intricacies of BeautifulSoup. I did a find for a specific 'select' tag using 'find(id=...)'. The returned results was the correct 'select' along with its options.
Find elsewhere
๐ŸŒ
DataStax
docs.datastax.com โ€บ en โ€บ developer โ€บ python-driver โ€บ 3.5 โ€บ upgrading
DataStax Python Driver - Upgrading
March 20, 2019 - If the expected size of the results is known, it is still possible to materialize a list using the iterator: results = session.execute("SELECT * FROM system.local") row_list = list(results) For backward compatability, ResultSet supports indexing. If the result is paged, all pages will be ...
Top answer
1 of 3
2

It has to do with targeting the specific parts of your html. Would something like this work?

response = requests.get('https://books.toscrape.com/')
# all html&css content-
soup = BeautifulSoup(response.content, 'html')
categories = soup.find("ul", class_ = 'nav nav-list' ).find('li').find('ul').find_all('a')

list = []

for i in categories:
    if i:
        list.append(i.text.strip())
print(list)
2 of 3
0

You can get rid of the unwanted characters by just strip text ("words") of the elements.

Solution

So you can use the parameter strip in get_text():

i.get_text(strip=True)

Example:

import requests
from bs4 import BeautifulSoup
url = 'https://books.toscrape.com/'
response = requests.get(url)
# all html&css content-
soup = BeautifulSoup(response.text, 'lxml')
categories = soup.select('ul.nav.nav-list li a' )
list = []

for i in categories:
    list.append(i.get_text(strip=True))
print(list)

Output

['Books', 'Travel', 'Mystery', 'Historical Fiction', 'Sequential Art', 'Classics', 'Philosophy', 'Romance', 'Womens Fiction', 'Fiction', 'Childrens', 'Religion', 'Nonfiction', 'Music', 'Default', 'Science Fiction', 'Sports and Games', 'Add a comment', 'Fantasy', 'New Adult', 'Young Adult', 'Science', 'Poetry', 'Paranormal', 'Art', 'Psychology', 'Autobiography', 'Parenting', 'Adult Fiction', 'Humor', 'Horror', 'History', 'Food and Drink', 'Christian Fiction', 'Business', 'Biography', 'Thriller', 'Contemporary', 'Spirituality', 'Academic', 'Self Help', 'Historical', 'Christian', 'Suspense', 'Short Stories', 'Novels', 'Health', 'Politics', 'Cultural', 'Erotica', 'Crime']

You may also take a look at your selector it could be more specific:

soup.select('ul.nav.nav-list li a')
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ attributeerror: resultset object has no attribute 'find'. you're probably treating a list of elements like a single element. did you call find_all() when you meant to call find()?
r/learnpython on Reddit: AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
January 11, 2023 -

I tried to extract the movie name from the IMDB database. https://www.imdb.com/chart/moviemeter/?ref_=nv_mv_mpm. I used the module, BeautifulSoup, and request.

movies = bs.find('tbody',class_='lister-list').find_all('tr')
title = movies.find('td',class_='titleColumn').a.text

I got the following error.

AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

pls help me

๐ŸŒ
Quora
quora.com โ€บ What-is-a-ResultSet-in-Python
What is a ResultSet in Python? - Quora
Answer: Typically a ResultSet is what you get back from a database after sending a SELECT query in the SQL language. If Python is talking to an SQlite database, then the ResultSet is from there. If Ruby is talking to the same database, it gets a ResultSet too. Java also gets a ResultSet. In o...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ while attempting to iterate over a beautiful soup resultset, an exception is thrown: typeerror: 'resultset' object cannot be interpreted as an integer
r/learnpython on Reddit: While attempting to iterate over a beautiful soup ResultSet, an exception is thrown: TypeError: 'ResultSet' object cannot be interpreted as an integer
July 2, 2022 -

I'm using beautiful soup in this exercise, and attempting to iterate over a ResultSet, which I have learned is not possible. At least not with my current code. The purpose of iterating over the ResultSet would be to gather the url name of each image, and write the url name as the filename when downloading the images. Is there a better way to achieve this?

The exercise is called Image Site Downloader, and it comes from in ATBS CH 12. From the book:

Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then downloads all the resulting images. You could write a program that works with any photo site that has a search feature.

#!python3
# image_downloader.py -- input a keyword and automatically download 
# images from https://unsplash.com/
# sys.argv[1] = keyword to search for

import requests
import os
import sys
import bs4
import lxml


def make_photo_dir():
    os.makedirs(f'{sys.argv[1]}', exist_ok=True)

def get_site_html_contents() -> bs4.element.ResultSet:
    res = requests.get('https://unsplash.com/s/photos/' + sys.argv[1])
    res.raise_for_status() # crash program if url not valid
    return bs4.BeautifulSoup(res.text, "lxml").select('.YVj9w')

def download_images(html_contents: bs4.element.ResultSet) -> None:
    make_photo_dir() # create dir using command line argument
    for url in len(range(html_contents)):
        image_url = html_contents.get('src')
        res = requests.get(image_url)
        res.raise_for_status()
        image_file = open(os.path.join(sys.argv[1], os.path.basename(url)), 'wb')
        for chunk in res.iter_content(100000):
            image_file.write(chunk)
        image_file.close()

def main():
    download_images(get_site_html_contents())

if __name__ == "__main__":
    main()

updated and tested download_images():

def download_images(self) -> None:
    '''
    create dir to store photos using search keyword as the name. iterate over
    beatuiful soup result set. use 'src' to pass url into image_url
    variable. use raise_for_status() to crash the program if url is not valid.
    except the MissingSchema exception. download photos into dir with the keyword +
    the index as the filename, + '.jpeg' as the file type.
    '''
    os.makedirs(self.keyword, exist_ok=True)  # make dir to store photos
    for index, url in enumerate(self.parse_site_html_contents()):
        image_url = url.get('src')
        try:
            res = requests.get(image_url)
            res.raise_for_status()
        except requests.exceptions.MissingSchema:
            continue
        image_file = open(os.path.join(self.keyword + '\\' + self.keyword + str(index) + '.jpeg'),'wb')
        for chunk in res.iter_content(100000):
            image_file.write(chunk)
        image_file.close()
๐ŸŒ
GitHub
github.com โ€บ influxdata โ€บ influxdb-python โ€บ blob โ€บ master โ€บ influxdb โ€บ resultset.py
influxdb-python/influxdb/resultset.py at master ยท influxdata/influxdb-python
October 29, 2024 - Python client for InfluxDB. Contribute to influxdata/influxdb-python development by creating an account on GitHub.
Author ย  influxdata
๐ŸŒ
MySQL
dev.mysql.com โ€บ doc โ€บ x-devapi-userguide-shell-python โ€บ en โ€บ working-with-sql-result-sets.html
MySQL :: X DevAPI User Guide for MySQL Shell in Python Mode :: 9.5 Working with SQL Result Sets
And if multiple result sets are returned, any of the result sets may be empty too. The following example assumes that the procedure my_proc exists. res = mySession.sql('CALL my_proc()').execute() if res.has_data(): row = res.fetch_one() if row: print('List of rows available for fetching.') while row: print(row) row = res.fetch_one() else: print('Empty list of rows.') else: print('No row result.')
๐ŸŒ
Readthedocs
influxdb-python.readthedocs.io โ€บ en โ€บ latest โ€บ resultset.html
Query response object: ResultSet โ€” InfluxDB 5.3.1 documentation
Its get_points method can be used to retrieve points generators that filter either by measurement, tags, or both. Using rs.get_points() will return a generator for all the points in the ResultSet. Using rs.get_points('cpu') will return a generator for all the points that are in a series with measurement name cpu, no matter the tags. rs = cli.query("SELECT * from cpu") cpu_points = list...
๐ŸŒ
Readthedocs
sdss-marvin.readthedocs.io โ€บ en โ€บ latest โ€บ query โ€บ results โ€บ results_set.html
The ResultSet Object โ€” Marvin 2.8.3.dev0 documentation
Your query results come as a Marvin marvin.tools.results.ResultSet object. As ResultSet is sub-classed from a Python list, it behaves exactly as a Python list object. ResultSet contains a list of query results, where each item in the list is a Marvin ResultRow object.
Top answer
1 of 5
36

If you have an iterable in Python, to make a list, one can simply call the list() built-in:

list(cursor.fetchall())

Note that an iterable is often just as useful as a list, and potentially more efficient as it can be lazy.

Your original code fails as it doesn't make too much sense. You loop over the rows and enumerate them, so you get (0, first_row), (1, second_row), etc... - this means you are building up a list of the nth item of each nth row, which isn't what you wanted at all.

This code shows some problems - firstly, list() without any arguments is generally better replaced with an empty list literal ([]), as it's easier to read.

Next, you are trying to loop by index, this is a bad idea in Python. Loop over values, themselves, not indices you then use to get values.

Also note that when you do need to build a list of values like this, a list comprehension is the best way to do it, rather than creating a list, then appending to it.

2 of 5
17

When I used the answer from Sudhakar Ayyar, the result was a list of lists, as opposed to the list of tuples created by .fetchall(). This was still not what I wanted. With a small change to his code, i was able to get a simple list with all the data from the SQL query:

cursor = connnect_db()

query = "SELECT * FROM `tbl`"

cursor.execute(query)

result = cursor.fetchall() //result = (1,2,3,) or  result =((1,3),(4,5),)

final_result = [i[0] for i in result]

Additionally, the last two lines can be combined into:

final_result = [i[0] for i in cursor.fetchall()]
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 58687605 โ€บ sql-resultset-python-list-to-dictionary
SQL Resultset (python list) to dictionary - Stack Overflow
Please include the exact code. Joachim's suggestion is right. It is a question of having {} around your data. But I want to see why you get () around your key value pairs. To convert a list of lists to a dictionary do l=[[4,5],[6,7] ] d = dict(l).