I created a search engine in Django and bs4 that scrapes search results from the Ask.com search engine. I would like when Django fetches search results from Ask, it checks the value of the X-Frame-Options header in order to give a value to my notAccept boolean depending on the result of the condition.
I took inspiration from this page of the Django documentation and also from this other page and after testing a proposed answer, I modified my code like this:
def search(request):
. . .
final_result = []
for page_num in range(1, max_pages_to_scrap+1):
url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num)
res = requests.get(url)
soup = bs(res.text, 'lxml')
result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'})
for result in result_listings:
result_title = result.find(class_='PartialSearchResults-item-title').text
result_url = result.find('a').get('href')
result_desc = result.find(class_='PartialSearchResults-item-abstract').text
final_result.append((result_title, result_url, result_desc))
for header in final_result[1]: #the error is generated here
response = requests.get(header)
if response['X-Frame-Options'] in ["DENY", "SAMEORIGIN"]:
head = True
notAccept = bool(head)
else:
notAccept = bool(False)
But when I test, I get in the terminal the following errors:
Internal Server Error: /search
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\user\Documents\AAprojects\Whelpsgroups1\searchEngine\search\views.py", line 29, in search
for header in final_result[1]:
IndexError: list index out of range
[17/Sep/2022 23:28:40] "GET /search?csrfmiddlewaretoken=t57w6QZSzkgsKoNJWXrjotBRdKSNxBBxzfzPnUC6N7kXfs5pMyGWcjQUYcrT13Ds&search=moto HTTP/1.1" 500 88593
I don't know how to solve this problem.Thank you!