Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beautiful Soup 'ResultSet' object has no attribute 'text'

from bs4 import BeautifulSoup
import urllib.request
import win_unicode_console
win_unicode_console.enable()


link = ('https://pietroalbini.io/')  
req = urllib.request.Request(link, headers={'User-Agent': 'Mozilla/5.0'})
url = urllib.request.urlopen(req).read()

soup =  BeautifulSoup(url, "html.parser")
body = soup.find_all('div', {"class":"wrapper"})

print(body.text)

Hi, I have a problem with Beautiful Soup, if I run this code without ".text" at the end it show me a list of div but if I add ".text" at the end come the error

Traceback (most recent call last): File "script.py", line 15, in print(body.text) AttributeError: 'ResultSet' object has no attribute 'text'

like image 579
Frank Avatar asked Mar 18 '16 17:03

Frank


2 Answers

find_all returns a ResultSet object which you can iterate over using a for loop. What you can do is:

for wrapper in body.find_all('div', {"class":"wrapper"}):
   print wrapper.text
like image 65
Ahmed Dhanani Avatar answered Nov 08 '22 15:11

Ahmed Dhanani


If you'll type:

print(type(body))

you'll see body is <class 'bs4.element.ResultSet'> It means all the elements that match the class. You can either iterate over them:

for div in body:
    print(div.text)

Or if you know you only have div, you can use find instead:

div = soup.find('div', {"class":"wrapper"})
div.text
like image 24
Mikhail Gerasimov Avatar answered Nov 08 '22 13:11

Mikhail Gerasimov