Python парсинг gdz.ru
Я написал код, но почему то на вывод идет только {}. Прошу помочь с поиском ошибки в коде.
import requests
from bs4 import BeautifulSoup
response = requests.get('https://gdz.ru/')
page_content = BeautifulSoup(response.content, "html.parser")
lessons_response = page_content.find_all('td', {'class' : 'table-section-heading'})
lessons = dict()
books_count = 0
for i in lessons_response:
try:
lesson_response1 = BeautifulSoup(requests.get('https://gdz.ru'+i.a['href']).content, "html.parser")
lesson_content = lesson_response1.find_all('a', {'class' : 'book book-regular text-undecorated'})
title = lessons[i.a['title']]
for j in lesson_content:
class_find = j['href'].find('class-')+6
class_num = int(j['href'][class_find] + j['href'][class_find+1].replace('/', ''))
if not class_num in title:
title[class_num] = {}
title[class_num][j['title'].replace('\n', '')] = 'https://gdz.ru'+j['href']
books_count+=1
except(KeyError):
pass
На вывод должно идти (примерно):
>>>lessons
{
'Алгебра':{
1:{
'Автор1': 'Ссылка1',
'Автор2': 'Ссылка2'
}
},
2:{
'Автор1': 'Ссылка1',
'Автор2': 'Ссылка2'
}
},
'Геометрия':{
1:{
'Автор1': 'Ссылка1',
'Автор2': 'Ссылка2'
}
},
2:{
'Автор1': 'Ссылка1',
'Автор2': 'Ссылка2'
}
}
}
На самом деле:
>>> lessons
{}
Заранее огромное спасибо за помощь!
Ответы (1 шт):
Автор решения: YoungProgrammer
→ Ссылка
Вот рабочий код:
import requests
from bs4 import BeautifulSoup
response = requests.get('https://gdz.ru/')
page_content = BeautifulSoup(response.content, "html.parser")
lessons_response = page_content.find_all('td', {'class' : 'table-section-heading'})
lessons = dict()
books_count = 0
for i in lessons_response:
try:
lesson_response1 = BeautifulSoup(requests.get('https://gdz.ru'+i.a['href']).content, "html.parser")
lesson_content = lesson_response1.find_all('a', {'class' : 'book book-regular text-undecorated'})
if not i.a['title'] in lessons:
lessons[i.a['title']] = {}
for j in lesson_content:
class_find = j['href'].find('class-')+6
class_num = int(j['href'][class_find] + j['href'][class_find+1].replace('/', ''))
if not class_num in lessons[i.a['title']]:
lessons[i.a['title']][class_num] = {}
lessons[i.a['title']][class_num][j['title'].replace('\n', '')] = 'https://gdz.ru'+j['href']
books_count+=1
except KeyError as err:
print("KeyError: {0}".format(err))
Обратите внимание на эту строчку:
if not i.a['title'] in lessons:
lessons[i.a['title']] = {}
У Вас не создавались имена предметов, поэтому была ошибка KeyError.