Reputation: 159
I'm trying to scrape the product titles, price, and stock from books.toscrape.com. However, I'm stuck with the error AttributeError: 'NavigableString' object has no attribute 'text'. What is NavigableString? I don't see it in my code. And what's the problem with the attribute 'text'?
import requests
from bs4 import BeautifulSoup
url = "http://books.toscrape.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml' )
stock = soup.find_all('p', class_='instock availability')
price = soup.find_all('p', class_='price_color')
title = soup.find_all('h3')
for i in range(0, 2):
quoteTitles = title[i].find('a')
for quoteTitle in quoteTitles:
print(quoteTitle.text.strip('\n'))
print(price[i].text.strip('Â'))
print(stock[i].text.strip('\n'))
Here is the error code below:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-41-1e5301201749> in <module>
10 quoteTitles = title[i].find('a')
11 for quoteTitle in quoteTitles:
---> 12 print(quoteTitle.text.strip('\n'))
13 print(price[i].text.strip('Â'))
14 print(stock[i].text.strip('\n'))
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/bs4/element.py in __getattr__(self, attr)
914 return self
915 else:
--> 916 raise AttributeError(
917 "'%s' object has no attribute '%s'" % (
918 self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'text'
Upvotes: 0
Views: 999
Reputation: 1016
print(quoteTitle.text.strip('\n'))
quoteTitle doesnot have any object as text. if you want to print qoute text , print direct quoteTitle.
print(quoteTitle)
Try this :
for i in range(0, 2): // fpr print all the detail change this for loop with `for i in range(0, len(title)):`.
quoteTitles = title[i].find('a')
for quoteTitle in quoteTitles:
print(quoteTitle)
#print(quoteTitle.text.strip('\n'))
print(price[i].text.strip('Â'))
print(stock[i].text.strip())
Output will be :
A Light in the ...
£51.77
In stock
Tipping the Velvet
£53.74
In stock
Upvotes: 1