Получение объекта 'NoneType' не имеет атрибута 'text' error с BeautifulSoup - PullRequest
0 голосов
/ 15 марта 2020

Я новичок в python и dyjan go. Я пытаюсь сделать скребок с помощью BeautifulSoup. На моем сайте есть форма поиска, где пользователь ищет товары, которые используют BeautifulSoup, чтобы просмотреть amazon.in, чтобы показать результаты пользователю.

Все работает нормально, но иногда выдает два типа ошибок, которые иногда дают мне ошибка:

File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: myapp_search.search

The above exception was the direct cause of the following exception:

и иногда выдает ошибку:

File "C:\Users\Ahmed\codelist\myapp\views.py", line 24, in new_search
    post_title = post.find(class_='a-section').text
AttributeError: 'NoneType' object has no attribute 'text'
[15/Mar/2020 13:34:15] "POST /new_search HTTP/1.1" 500 87165

my views.py

import requests
from bs4 import BeautifulSoup
from django.shortcuts import render
from requests.compat import quote_plus
from . import models

BASE_AMAZON_URL = 'https://www.amazon.in/s?k={}'

def home(request):
    return render(request, 'base.html')

def new_search(request):
    search = request.POST.get('search')
    models.Search.objects.create(search=search)
    final_url = BASE_AMAZON_URL.format(quote_plus(search))
    response = requests.get(final_url)
    data = response.text
    soup = BeautifulSoup(data, features='html.parser')

    post_listings = soup.find_all('', {'class': 's-result-list'})

    final_postings = []
    for post in post_listings:
        post_title = post.find(class_='a-section').text
        post_url = post.find('a').get('href')
        post_price = post.find(class_='a-price').text

        final_postings.append((post_title, post_url, post_price))

    stuff_for_frontend = {
    'search': search,
    'final_postings': final_postings,
    }
    return render(request, 'myapp/new_search.html', stuff_for_frontend)

my new_search. html

{% extends 'base.html' %}

{% block content %}
    <h2 style="text-align: center;">{{ search | title }}</h2>

    {% for post in final_postings %}
    <p>{{ post.0 }}</p>
    <p>{{ post.1 }}</p>
    <p>{{ post.2 }}</p>
    {% endfor %}


{% endblock content %}

1 Ответ

1 голос
/ 15 марта 2020

Согласно документации Beautiful Soup :

AttributeError: 'NoneType' object has no attribute 'foo' - Это обычно происходит потому, что вы вызвали find(), а затем попытались получить доступ к атрибуту .foo результата. , Но в вашем случае find() ничего не нашел, поэтому он возвратил None вместо возврата тега или строки. Вам необходимо выяснить, почему ваш вызов find() ничего не возвращает.

Не удалось найти элемент, который вы искали в этой строке, и вернул None: post_title = post.find(class_='a-section').text

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...