如果它只给我一个品牌错误,我该如何解决它
Traceback(最近一次调用):文件"d:/python/davago.py",第15行品牌=属性。Find ('h3', class_ = ' productiitem -vendor').text.strip()AttributeError: 'NoneType'对象没有属性'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)
您应该首先找到'productgrid- items',然后查看其中的每个项目。"productitem"类可能还有另一种用法,但没有h3在里面,这就是为什么你会得到异常:
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)
如果您看到最后三个内容没有供应商名称,那么您可以使用try
和except
块来处理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')
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)