Google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup
я пытаюсь сделать поиск google с помощью BeautifulSoup в проекте сайта socialnetwork django я скачал его как open source и когда я пытаюсь сделать это я получаю сообщение об ошибке cannot unpack non-iterable NoneType object
thats search.py
импорт запросов из bs4 import BeautifulSoup
done
def google(s): ссылки = [] текст = []
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
headers = {"user-agent": USER_AGENT}
r=None
if r is not None :
r = requests.get("https://www.google.com/search?q=" + s, headers=headers)
soup = BeautifulSoup(r.content, "html.parser")
for g in soup.find_all('div', class_='yuRUbf'):
a = g.find('a')
t = g.find('h3')
links.append(a.get('href'))
text.append(t.text)
return links, text
и это view.py
def results(request): if request.method == "POST":
result = request.POST.get('search')
google_link,google_text = google(result)
google_data = zip(google_link,google_text)
if result == '':
return redirect('Home')
else:
return render(request,'results.html',{'google': google_data })
и это шаблон
{% for i,j in google %}
<a href="{{ i }}" class="btn mt-3 w-100 lg-12 md-12">{{ j }}</a><br>
{% endfor %}
i reseve the message cannot unpack non-iterable NoneType object for google_link,google_text = google(result)
not None возвращает True, если объекты не идентичны. В вашем случае r=None и 'if r is not None' сразу проверяется, поэтому возвращается False. Все строки ниже оператора if не задействованы. Возможно, из-за этого: невозможно распаковать неитерабельный объект NoneType. Потому что он не существует
Остальная часть кода работает. Я немного изменил его, и если ваш не работает, используйте мой. Поисковое слово вводится в поле формы, в случае успешного сохранения формы, результат передается в представление 'results'. Если он пуст, то на странице будет показано: 'result = empty'.
views.py
def google(s):
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
headers = {"user-agent": USER_AGENT}
r = None
links = []
text = []
r = requests.get("https://www.google.com/search?q=" + s, headers=headers)
soup = BeautifulSoup(r.content, "html.parser")
for g in soup.find_all('div', class_='yuRUbf'):
a = g.find('a')
t = g.find('h3')
links.append(a.get('href'))
text.append(t.text)
return links, text
def form(request):
return render(request, 'bboard/form.html')
def results(request):
if request.method == 'POST':
result = request.POST.get('search')
google_link, google_text = google(result)
google_data = zip(google_link, google_text)
if result == '':
return HttpResponseNotFound('<h1>result = empty</h1>')
else:
return render(request, 'bboard/results.html', {'google': google_data})
form.hml
<form method='post' action="{% url 'results'%}">
{% csrf_token %}
<p>Name:<br> <input name='search'/></p>
<input type='submit' value='Send'/>
</form>
results.html
{% for i,j in google %}
<a href="{{ i }}" class="btn mt-3 w-100 lg-12 md-12">{{ j }}</a><br>
{% endfor %}
urls.py
urlpatterns = [
path('form/', form, name='form'),
path('results/', results, name='results'),
]