BeautifulSoup метод .get
Подскажите что я делаю не так ? данных нет и выходит ошибка по методу .get
import requests
from bs4 import BeautifulSoup
import lxml.html
from bs4.diagnose import lxml_trace
url1 = 'https://4lapy.ru/catalog/koshki/korm-koshki/sukhoy/'
HEAD = {
'User-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.141 Mobile Safari/537.36',
'accept': '*/*'}
def get_html(url, params=None):
r = requests.get(url, headers=HEAD, params=params)
return r
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
# item = soup.find_all('div', class_='b-common-item')
item = soup.find_all('div', class_='b-common-item__info-center-block')
catalog = []
for items in item:
catalog.append({
'title': items.find('span', class_='b-common-item__image-wrap"').get_text(strip=True),
'link': items.find('a', class_='b-common-item__description-wrap js-item-
link').get('href'),
})
print(catalog)
def parse():
html = get_html(url1)
get_content(html.text)
parse()
C:\Users\Maks\PycharmProjects\Parcer_Python_Max\venv\Scripts\python.exe C:/Users/Maks/PycharmProjects/Parcer_Python_Max/main.py
Traceback (most recent call last):
File "C:/Users/Maks/PycharmProjects/Parcer_Python_Max/main.py", line 47, in <module>
parse()
File "C:/Users/Maks/PycharmProjects/Parcer_Python_Max/main.py", line 44, in parse
get_content(html.text)
File "C:/Users/Maks/PycharmProjects/Parcer_Python_Max/main.py", line 33, in get_content
'title': items.find('span', class_='b-common-item__image-wrap"').get_text(strip=True),
AttributeError: 'NoneType' object has no attribute 'get_text'
Process finished with exit code 1
Ответы (1 шт):
Автор решения: Dmitry
→ Ссылка
Такая ошибка возникает когда вы пытаетесь вызвать метод у сущности None.
Вот список доступных
>>> dir(None)
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__le__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
items.find() у вас возвращает этот самый None и как видно из списка, метода get_text у него нет.
Решение: прежде чем использовать метод, убедитесь, что items.find() возвращает нужную вам сущность (объект)
Решение без привязки к bs4:
match = items.find('span', class_='b-common-item__image-wrap"')
catalog.append({
'title': match.get_text(strip=True) if match else None,
'link': items.find('a', class_='b-common-item__description-wrap js-item-
link').get('href'),
})