As it give me error an on brand only how should i resolved it
Traceback (most recent call last): File "d:/python/davago.py", line 15, in brand= property.find('h3', class_ = 'productitem--vendor').text.strip() AttributeError: 'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
from bs4 import *
import pandas as pd
import time
url = 'https://dvago.pk/collections/cardio-vascular-system?page=1&grid_list=grid-view'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
content = soup.find_all('div', class_ = 'productitem')
#print(content)
for property in content:
names= property.find('div', class_ = 'productitem--info')
name= names.find('h2', class_ = 'productitem--title').text.strip()
brand= property.find('h3', class_ = 'productitem--vendor').text.strip()
print(name,brand)
CodePudding user response:
If you see last three content does not have vendor name so you can use try
and except
block to handle exception
and print appropraite statement
import requests
from bs4 import BeautifulSoup
from bs4 import *
import pandas as pd
import time
url = 'https://dvago.pk/collections/cardio-vascular-system?page=1&grid_list=grid-view'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
content = soup.find_all('div', class_ = 'productitem')
#print(content)
for property in content:
names= property.find('div', class_ = 'productitem--info')
try:
name= names.find('h2', class_ = 'productitem--title').text.strip()
except AttributeError:
name="Company name not available"
try:
brand= property.find('h3', class_ = 'productitem--vendor').text.strip()
except AttributeError:
brand="Brand name not available"
print("Company Name:",name)
print("Brand Name:",brand)
CodePudding user response:
You should find 'productgrid--items' first then you go over each item in there. There is probably another use for the 'productitem' class but without the h3 in it and that's why you are getting the exception :
import requests
from bs4 import BeautifulSoup
from bs4 import *
# import pandas as pd
# import time
url = 'https://dvago.pk/collections/cardio-vascular-system?page=1&grid_list=grid-view'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
aaa = soup.find('div', class_='productgrid--items') ## <------
content = aaa.find_all('div', class_='productitem') ## <------
# print(content)
for property in content:
names = property.find('div', class_='productitem--info')
name = names.find('h2', class_='productitem--title').text.strip()
brand = property.find('h3', class_='productitem--vendor').text.strip()
print(name, brand)